Potential Memory Leak for ABRecordCopyValue

ぃ、小莉子 提交于 2019-12-11 07:18:51

问题


I am building an app that requres me to load all the contacts in the datasource of the table from the iPhone AddressBook. On running

Build and Analyze

for the following snippet

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

I am getting a potential memory leak for the line

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

I am really tired of fixing it but was unable to. Kindly help me out.

Any kind of help would be highly appriciated.

Thanks in advance!!


回答1:


You aren't releasing the result of ABRecordCopyValue; try assigning it to a variable and release it and the end of the loop. Using a variable will also make your code a lot easier to read and highlight the cause of these issues better.

BTW, you are also calling ABRecordCopyValue twice with the same arguments, you should only do it once (using a variable as mentioned above).




回答2:


I think you can do like below:

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



回答3:


You can directly bridge to an NSString. It may be a little more clear:

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


来源:https://stackoverflow.com/questions/4991564/potential-memory-leak-for-abrecordcopyvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!