Question

I use this code to get the last name of ABPerson

CFStringRef lastNameRef = ABRecordCopyValue((ABRecordRef)personRecordRef, kABPersonLastNameProperty);
NSString *friendLastName = (NSString*)lastNameRef;
CFRelease(lastNameRef);

it work fine when the value of last name is not equal to NULL but when the this value is NULL the application crash at the third line because I try to relese NULL

the question is witch is the best way to releasing the CFString in this case without causing the crash of the application

Was it helpful?

Solution

Just use an if to check for NULL.

if (lastNameRef != NULL)
    CFRelease(lastNameRef);

OTHER TIPS

CFRelease is old C style code. One should check for NULL before calling CFRelease as also set lastNameRef to NULL after calling CFRelease.

if (lastNameRef != NULL) { CFRelease(lastNameRef); lastNameRef = NULL; }

CFRelease expects a non-NULL pointer. You could check for that with an if statement, but it is easier to simply release or autorelease friendLastName instead:

CFStringRef lastNameRef = ABRecordCopyValue((ABRecordRef)personRecordRef, kABPersonLastNameProperty);
NSString *friendLastName = (NSString*)lastNameRef;
// use friendLastName
[friendLastName release];

or

CFStringRef lastNameRef = ABRecordCopyValue((ABRecordRef)personRecordRef, kABPersonLastNameProperty);
NSString *friendLastName = (NSString*)lastNameRef;
[friendLastName autorelease];
// use friendLastName

As you don't seem to use lastNameRef, you could also inline that variable:

NSString *friendLastName = (NSString*)ABRecordCopyValue((ABRecordRef)personRecordRef, kABPersonLastNameProperty);
// use friendLastName
[friendLastName release];

or

NSString *friendLastName = (NSString*)ABRecordCopyValue((ABRecordRef)personRecordRef, kABPersonLastNameProperty);
[friendLastName autorelease];
// use friendLastName
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top