Core Foundation Object Lifecycle Management

The life span of a Core Foundation object is determined by its reference count—an internal count of the number of clients who want the object to persist. When you create or copy an object in Core Foundation, its reference count is set to one. Subsequent clients can claim ownership of the object by calling CFRetain which increments the reference count. Later, when you have no more use for the object, you call CFRelease. When the reference count reaches 0, the object’s allocator deallocates the object’s memory.

Retaining Object References

To increment the reference count of a Core Foundation object, pass a reference to that object as the parameter of the CFRetain function:

/* myString is a CFStringRef received from elsewhere */
myString = (CFStringRef)CFRetain(myString);

Releasing Object References

To decrement the reference count of a Core Foundation object, pass a reference to that object as the parameter of the CFRelease function:

CFRelease(myString);

Copying Object References

When you copy an object, the resulting object has a reference count of one regardless of the reference count of the original object. For more on copying objects, see “Copy Functions.”

Determining an Object's Retain Count

If you want to know the current reference count of a Core Foundation object, pass a reference to that object as the parameter of the CFGetRetainCount function:

CFIndex count = CFGetRetainCount(myString);

Note, however, that there should typically be little need to determine the reference count of a Core Foundation object, except in debugging. If you find yourself needing to know the retain count of an object, check that you are properly adhering to the ownership policy rules (see “Ownership Policy”).