简体   繁体   中英

Memory leak when declaring NSString from ABRecordCopyValue

I am using the following line of code...

NSString *clientFirstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);

The 'analyse' feature on Xcode is saying that this giving rise to a potential memory leak. I am not releasing clientFirstName at all as I have neither alloc or retain 'd it.

However, I am conscious that ABRecordCopyValue may not be returning an object as say a command like [NSMutableArray arrayWithArray:someArray] would which might mean I am indeed creating a new object that I control and must release.

Keen to hear thoughts...

Any sort of copy returns an object with a retainCount of 1, so you need to release it via CFRelease() .

See the doc :

You are responsible for releasing this object.

Refer to this link. It has same as yours:

NSString potential leak

Refer to answer of KennyTM :

ABMultiValueCopyValueAtIndex is a "Copy" function, which follows the "Create Rule" . You need to call CFRelease to release it after finish using it.

 NSString *contactEmail = (NSString *)ABMultiValueCopyValueAtIndex(emailInfo, 0); ... if (contactEmail != nil) CFRelease((CFTypeRef) contactEmail); 

Release your object clientFirstName using CFRelease .

Add the code below:

if(clientFirstName != nil)
{
     CFRelease((CFTypeRef) clientFirstName);
}

NOTE: Do not forget to check if clientFirstName is not nil. It is better to have a practice of checking that object is not nil before executing any function on it as it saves us from potential crashes though not in this case, but in many cases

EDIT:

Also as @Dondragmer says in one of the comments below:

I think even

[clientFirstName release];

should solve the problem.

Let me know if you need more help.

Hope this helps you.

I don't fully understand how ObjectiveC reference counting works, but a small update in code fixed the Analyze warning:

Before:

NSString *firstName = (__bridge NSString*) ABRecordCopyValue(person, kABPersonFirstNameProperty);

After

NSString *firstName = (__bridge_transfer NSString*) ABRecordCopyValue(person, kABPersonFirstNameProperty);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM