< Previous PageNext Page > Hide TOC

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.

Contents:

Retaining Object References
Releasing Object References
Copying Object References
Determining an Object's Retain Count


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);

Important: You should never directly deallocate a Core Foundation object (for example, by calling free on it). When you are finished with an object, call the CFRelease function and Core Foundation will properly dispose of it.

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”).



< Previous PageNext Page > Hide TOC


© 2008 Apple Inc. All Rights Reserved. (Last updated: 2008-10-15)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.