The policy of object ownership can be distilled from the answer to the question: Am I responsible for disposing of this object? The answer is this:
The functions of Core Foundation have names that indicate when you "own" a returned object. The object-creation functions embed "Create" in the name and the object-duplication functions embed "Copy" in the name, for example:
/* from CFBag.h */ CF_EXPORT CFBagRef CFBagCreate(CFAllocatorRef allocator, const void **values, CFIndex numValues, const CFBagCallBacks *callBacks); CF_EXPORT CFMutableBagRef CFBagCreateMutableCopy(CFAllocatorRef allocator, CFIndex capacity, CFBagRef bag); /* from CFTimeZone.h */ CF_EXPORT CFDictionaryRef CFTimeZoneCopyAbbreviationDictionary(void); CF_EXPORT CFTimeZoneRef CFTimeZoneCreateWithTimeIntervalFromGMT(CFAllocatorRef allocator, CFTimeInterval ti);
Creation functions in Core Foundation use a passed-in allocator to create the requested object; functions that copy objects use the allocator of the receiver. Although the CFBag function
CFBagCreateMutableCopy
in the code shown above has both "Create" and "Copy" in its name, it is a creation function not only because "Create" is in the function name but because the first argument is of type
CFAllocatorRef
. The "Copy" in this function is a hint that the function takes a
CFBagRef
argument and produces a duplicate of the object. It also refers to what happens to the element objects of the source collection: they are copied to the newly created CFBag. The secondary "Copy" and "NoCopy" substrings of function names indicate how objects owned by some source objects are treated, that is, whether they are copied or retained.
If you receive an object from any Core Foundation function other than a creation or copy function, such as a Get function, you cannot be certain of the object's life span. For example, if the object's "containing" or owning object is deallocated the "contained" object is deallocated too. To ensure the persistence of such an object you can retain it (using the
CFRetain
function) or, in some cases, copy it.
ImportantNever release an object that you don't own, such as an object returned from a Get function. Doing so could have serious and unpredictable consequences, such as runtime errors.