Core Foundation objects and retain/release messages
Let's say we have some Core Foundation objects, such 开发者_开发问答as CGColorRef, that are added to an NSArray like this:
CGColorRef color = ...;
NSArray *array = [NSArray arrayWithObject:(id)color];
Since arrays retain their contents, color receives a retain message (not CFRetain(), right?). What happens in this case from memory management point of view?
From Core Foundation Design Concepts:
Note from the example that the memory management functions and methods are also interchangeable—you can use
CFReleasewith a Cocoa object andreleaseandautoreleasewith a Core Foundation object.
It doesn't specifically mention retain, but, in practice, that works as well, as do copy (various classes' CFFooCreateCopy) and description (CFCopyDescription). The last is how you can pass CF objects as the value for a %@ formatting specification when using NSLog and other string-formatting functions and methods.
The result is the same: retain does the same as CFRetain, release does the same as CFRelease, etc.
A few things to be aware of:
- Prior to iOS 7 and OS X 10.9, there is no CF counterpart function to NSObject's
autoreleasemethod. (7 and 10.9 brought theCFAutoreleasefunction.) If you're not using ARC, then, as mentioned in the documentation quoted above, you can sendautoreleaseto a CF object, and it works the same as on an NSObject. - You can send a message to
nil, but you can't call CF functions onNULL(you'll crash). Quartz has some class-specific functions, such asCGContextRetain/Release, that include aNULLcheck; whether you want to use those or always do your ownNULLchecks is a matter of style. - CF's retain and release functions work under garbage collection, whereas
retainandreleasemessages are no-ops (as if sent tonil). Doesn't matter unless you're working on a GC'd Mac app, in which case you will need to useCFRetainandCFReleaseon CF objects. - Similarly, under ARC,
retainandreleasemessages will be illegal and CF objects won't be automatically reference-counted. You will need to useCFRetainandCFReleaseon CF objects. - Collections always do the right thing, as documented. Usually, this means a strong reference. Outside of GC, that means the collection (array, dictionary, etc.) will retain and release its objects, whether automatically (by assignments, if its code is ARCified) or manually (by explicit
retainandreleasemessages).
加载中,请稍侯......
精彩评论