2011-02-14 71 views
1

我正在構建一個應用程序,它要求我從iPhone AddressBook中的表的數據源中加載所有聯繫人。在運行ABRecordCopyValue的潛在內存泄漏

建立與分析

以下片斷

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

您不會發布ABRecordCopyValue的結果;嘗試將它分配給一個變量並釋放它並結束循環。使用變量還會使代碼更易於閱讀,並更好地突出顯示這些問題的原因。

順便說一句,你也用相同的參數兩次調用ABRecordCopyValue,你應該只做一次(使用上面提到的變量)。

+0

非常感謝vickink ......這個工作對我來說...:)......你救了我的一天 – devsri 2011-02-14 11:33:06

+0

嘿能請你幫我在這如以及http://stackoverflow.com/questions/4991247/getting-warning-in-setting-delegate-for-abpeoplepickernavigationcontroller謝謝 – devsri 2011-02-14 11:41:12

2

我認爲你可以做象下面這樣:

CFTypeRef copiedValue = ABRecordCopyValue([allPeople objectAtIndex:i], kABPersonFirstNameProperty); 
name = [[NSString stringWithFormat:@"%@", copiedValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
CFRelease(copiedValue); 
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);