John-Paul Gignac
John-Paul Gignac

Reputation: 291

Can ARC manage non-toll-free-bridged Core Foundation objects?

If I have a non-toll-free-bridged Core Foundation object, can I safely transfer ownership to ARC, or is that privilege reserved for toll-free-bridged types?

For example:

- (id)myBundle {
    CFBundleRef b = CFBundleCreate(NULL, self.bundleURL);
    return b == NULL ? nil : (__bridge_transfer id)b;
}

- (UInt32)myBundleVersionNumber {
    return CFBundleGetVersionNumber((__bridge CFBundleRef)self.myBundle);
}

Upvotes: 5

Views: 299

Answers (1)

CRD
CRD

Reputation: 53010

Every CoreFoundation object (CFTypeRef) is also an Objective-C object (id).

In the old days, before CFAutorelease() was introduced in 10.9, non-ARC code would autorelease CoreFoundation objects using the [(id)<CFTypeRef> autorelease] idiom which was possible due to CoreFoundation objects being Objective-C objects.

The correspondence is why in ARC a CoreFoundation object can be __bridge_transfer'ed to ARC.

So the answer is yes, you can safely transfer ownership of any CoreFoundation object to ARC.

If you step through your sample code at the assembler level you will find ARC calling _objc_release which in turn will end up calling CFRelease.

Note: The toll-free bridged objects are those where there are exact equivalents in CoreFoundation and Objective-C so they can be used interchangeably.

Upvotes: 7

Related Questions