luffy
luffy

Reputation: 429

What is "CFRetain+CFAutorelease" behavior in iOS under ARC?

The test code below, if use CFRetain, test would not be dealloc, but use CFRetain+CFAutoRelease, test would be dealloc.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSObject *test = [NSObject new];

[test.rac_willDeallocSignal subscribeCompleted:^{
    NSLog(@"test will dealloc");
}];

NSLog(@"Retain count 1 is %ld", CFGetRetainCount((__bridge CFTypeRef)test));

//CFRetain((__bridge CFTypeRef)test);
CFRetain(CFAutorelease((__bridge CFTypeRef)test));

NSLog(@"Retain count 2 is %ld", CFGetRetainCount((__bridge CFTypeRef)test));

return YES;
}

The log output:

in case 1(use CFRetain only): Retain count 1 is 1 Retain count 2 is 2

in case2(use CFRetain+CFAutorelease): Retain count 1 is 1 Retain count 2 is 2 test will dealloc

Upvotes: 0

Views: 2590

Answers (1)

Duncan C
Duncan C

Reputation: 131418

ARC does not manage Core Foundation objects at all unless you use "bridging casts" to specifically put them under ARC control.

If you get a CF object using the create rule, you are responsible for releasing it or you will leak memory.

EDIT:

Looking at your code, you are playing games with NSObjects and casting them to CF Objects in order do CFRetain and CFAutorelease on them. Don't do that. Create real CF objects if you want to learn the behavior of CF objects. (CFString for example.)

CFAutorelease serves the same purpose in Core Foundation as it does in manual reference counted Foundation Classes. It adds the object to an autorelease pool, meaning it will get a CFRelease on the next pass through the event loop, or when the release pool is explicitly drained, whichever comes first. CFAutoRelease is useful for returning CFObjects as function results that the caller doesn't have to release himself/herself.

Upvotes: 4

Related Questions