解决潜在的内存泄漏问题

时间:2012-01-24 23:17:42

标签: objective-c ios memory-leaks core-foundation abaddressbook

在xcode

中运行分析工具后,我收到以下内存泄漏
//Getting memeory leak warning here "Potential leak of an object allocated and stored into 'phones'
ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);

//Getting potential leak error for line below
if (ABMultiValueGetCount(ABRecordCopyValue(ref, kABPersonPhoneProperty))!=0)
{
    //Getting potential leak error for line below
    CFStringRef pNumber = ABMultiValueCopyValueAtIndex(phones,0);
    phoneNumber = [NSString stringWithFormat:@"%@", (NSString *)pNumber];
    NSString *contactFirstLast = [NSString stringWithFormat: @"%@ %@", firstName, lastName];
}

如何解决这些泄漏?

2 个答案:

答案 0 :(得分:5)

ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);

if (ABMultiValueGetCount(phones) != 0)
{
    CFStringRef pNumber = ABMultiValueCopyValueAtIndex(phones,0);
    phoneNumber = [NSString stringWithFormat:@"%@", (NSString *)pNumber];
    NSString *contactFirstLast = [NSString stringWithFormat: @"%@ %@", firstName, lastName];
    CFRelease(pNumber);
}
CFRelease(phones);

答案 1 :(得分:3)

自复制pNumber后,您需要将其释放:CFRelease(pNumber)

您需要重做if条件,以便它使用phones,然后释放phones