1

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

构建和分析

对于以下代码段

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]];

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

任何形式的帮助都会受到高度评价。

提前致谢!!

4

3 回答 3

4

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

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

于 2011-02-14T11:27:03.940 回答
2

我认为您可以执行以下操作:

CFTypeRef copiedValue = ABRecordCopyValue([allPeople objectAtIndex:i], kABPersonFirstNameProperty);
name = [[NSString stringWithFormat:@"%@", copiedValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
CFRelease(copiedValue);
于 2012-05-31T05:47:17.350 回答
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);
于 2013-11-27T05:31:38.200 回答