Quote:
Originally Posted by marciokoko
I have written some code using the ABook framework, using ARC.
I am simply using a people picker and I used this:
Code:
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
//1. get values and set labels...
//1.a get the name
NSString *fname = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
self.fullName.text = fName;
[self dismissModalViewControllerAnimated:YES];
return NO;
}
So I understand Im casting a CFType (ABRecordCopyValue) and that causes a problem because of ARC.
At first I added this:
Code:
NSString *fname = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
But I was told that doesn't do anything to the retain count, and that I had to use CFBridgingRelease to release that CFType. How exactly do I use it?
|
Erica Sadun's new (and fantastic) "iOS 5 Developer's Cookbook" has an excellent section on ARC and using it with Core foundation classes. I was rather lost on using CF objects in ARC until I read about it there. I highly recommend buying her book. It is due to be released in 2 days on Amazon. Go order a copy now. Really. You won't regret it.
Anyway, in the meantime, here's the deal.
__bridge simply converts between CF and Objective C objects. It works in both directions. It does not adjust retain counts for you.
__bridge_transfer (or the macro CFBridgingRelease() ) converts a CF object to an NSObject. It is used for "toll-free bridged" CF objects. It lets you pass a CF object that you own to it's Objective C equivalent. The CF object is released in the process, and ARC takes ownership of the equivalent NSObject.
__bridge_retain (or the macro CFBridgingRetain() ) does the reverse of __bridge_transfer. It lets you convert an autoreleased NSObject to it's CF equivalent. The bridge CFRetains the resulting CF object, so you have to CFRelease it when you're done with it.
In your case, you are converting a CFString, which is toll-free bridged to NSString, to it's NSString equivalent. The ABRecordCopyValue method has copy in it's name, so it follows the "Create rule" for CF objects. You own it and need to release it. Thus, you should use this line:
Code:
NSString *fname = (NSString*) CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
after that line, fname holds a "strong" reference to the converted CFString, and will release it when it goes out of scope.