Reputation: 7195
I am getting contact details and am having memory problems in my shouldContinueAfterSelectingPerson method. I followed a tutorial and did this weeks ago but now when I click Product -> Analyze I get 'Potential leak of an object allocated on line' on these 3 lines:
[lastName setText:(__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty)];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateOfBirth setText:birthday];
When clicking on these errors I get (though only number 2 for the third line):
Call to a function 'ABRecordCopyValue' returns a Core Foundation object with a + 1 retain count
Object leaked: allocated object is not referenced later in this execution path and has a retain count of + 1
The full code is shown below:
- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
[firstName setText:(__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty)];
[lastName setText:(__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty)];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM d, yyyy"];
birthday = [dateFormatter stringFromDate:(__bridge NSDate *)ABRecordCopyValue(person, kABPersonBirthdayProperty)];
[dateOfBirth setText:birthday];
Is there a fix around this and how important is it that I do fix it? I have one other potential leak of an object in my code.
A final note: I am using ARC.
Upvotes: 1
Views: 1528
Reputation: 25740
Since the functions are returning new objects (they have copy in the name) you need to release those objects somehow.
This can be done by calling the appropriate method to release it, or by using __bridge_transfer
instead of __bridge
, which instructs ARC to take over the memory management and release it when needed.
Upvotes: 1
Reputation: 34912
You want this:
[lastName setText:(__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty)];
The reason you're seeing the warning from the analyser is that ABRecordCopyValue
returns a CFStringRef
with +1 retain count. You're then casting to an NSString*
but saying to ARC not to take ownership of the object. That means it won't automatically add in the release for you. So you need to tell ARC to take ownership during the cast into Objective-C object land which is done using __bridge_transfer
.
You could also have done:
CFStringRef string = ABRecordCopyValue(person, kABPersonLastNameProperty);
[lastName setText:(__bridge NSString *)string];
CFRelease(string);
Upvotes: 8