toll-free bridged objects, retain and release
-
11-04-2021 - |
문제
I'm currently looking at a NSMutableSet
created by the function CFSetCreateMutable()
. The documentation states that the return value of CFSetCreateMutable()
is toll-free bridged, meaning that I can simply cast it into a NSMutableSet
. Does this mean that sending it the release
message is perfectly valid? Am I always safe to assume that I can always treat such objects as if they were alloc
'ed via an NS-class?
해결책
Just imagine that CFSetCreateMutable()
is equivalent to [[NSMutableSet alloc] init] in that you have to release the object after you are done with it. If you are using ARC, you can cast a CFMutableSet to an NSMutableSet using a bridged cast: (__bridge_transfer NSMutableSet *)theCFSet
. This will tell ARC that it is responsible for releasing the set after it goes out of scope.
다른 팁
The documentation states that the return value of CFSetCreateMutable() is toll-free bridged, meaning that I can simply cast it into a NSMutableSet. Does this mean that sending it the release message is perfectly valid?
Yes. This is explicitly guaranteed in the docs:
Note from the example that the memory management functions and methods are also interchangeable—you can use
CFRelease
with a Cocoa object andrelease
andautorelease
with a Core Foundation object.
Am I always safe to assume that I can always treat such objects as if they were alloc'ed via an NS-class?
Not really: Currently, anything that exists in common between CFType and NSObject, such as -description
/CFCopyDescription
, works regardless of how you created the object, but they're not all explicitly guaranteed to work like the memory-management messages are.