ABRecordCopyValue的潜在内存泄漏

时间:2011-02-14 11:21:24

标签: memory-leaks abaddressbook

我正在构建一个应用程序,要求我从iPhone AddressBook加载表格数据源中的所有联系人。在运行

  

构建和分析

以下代码段

ABAddressBookRef addressBook = ABAddressBookCreate(); 
int nPeople = ABAddressBookGetPersonCount(addressBook); 
CFRelease(addressBook);

for(int i=0; i < nPeople; i++ ){
    //ABRecordRef person = [allPeople objectAtIndex:i];
    NSString *name = @"";
    if(ABRecordCopyValue([allPeople objectAtIndex:i], kABPersonFirstNameProperty) != NULL)
        name = [[NSString stringWithFormat:@"%@", ABRecordCopyValue([allPeople objectAtIndex:i], kABPersonFirstNameProperty)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    [dataSource addObject: name];
}

[allPeople release];

我的线路存在潜在的内存泄漏

name = [[NSString stringWithFormat:@"%@", ABRecordCopyValue([allPeople objectAtIndex:i], kABPersonFirstNameProperty)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

我真的厌倦了修复但却无法修复它。请帮助我。

任何形式的帮助都会受到高度关注。

提前致谢!!

3 个答案:

答案 0 :(得分:4)

您没有发布ABRecordCopyValue的结果;尝试将其分配给变量并释放它并循环结束。使用变量还可以使您的代码更容易阅读,并更好地突出显示这些问题的原因。

顺便说一句,你也用相同的参数调用ABRecordCopyValue两次,你应该只做一次(使用上面提到的变量)。

答案 1 :(得分:2)

我认为你可以这样做:

CFTypeRef copiedValue = ABRecordCopyValue([allPeople objectAtIndex:i], kABPersonFirstNameProperty);
name = [[NSString stringWithFormat:@"%@", copiedValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
CFRelease(copiedValue);

答案 2 :(得分:1)

您可以直接桥接到NSString。可能会更清楚一点:

CFTypeRef fn_typeref = ABRecordCopyValue(person, kABPersonFirstNameProperty);
CFTypeRef ln_typeref = ABRecordCopyValue(person, kABPersonLastNameProperty);

NSString * firstName = (__bridge NSString *) fn_typeref;
NSString * lastName  = (__bridge NSString *) ln_typeref;

NSLog(@"Name:%@ %@", firstName, lastName);

CFRelease(fn_typeref);    // releasing CFTypeRef
CFRelease(ln_typeref);

// use firstName and lastName down here
NSLog(@"Name:%@ %@", firstName, lastName);