Bha*_*n_m 1 iphone memory-leaks memory-management objective-c ios
当我分析我的项目以下代码给我泄漏警告.有没有办法解决我的内存泄漏问题?
警告 :
Potential leak of an object allocated on line 38 and stored into 'addressBook'
Run Code Online (Sandbox Code Playgroud)
贝娄是我的代码.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
m_tableDataArray = [[[NSMutableArray alloc] init]autorelease];
NSMutableArray *listDate = [[[NSMutableArray alloc] init]autorelease];
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *addresses = (NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
NSInteger addressesCount = [addresses count];
for (int i = 0; i < addressesCount; i++) {
ABRecordRef record = [addresses objectAtIndex:i];
NSString *firstName = (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty);
if(firstName != nil && lastName != nil){
NSString *contactFirstLast = [NSString stringWithFormat: @"%@ %@", firstName, lastName];
[listDate addObject:contactFirstLast];
}
[firstName release];
[lastName release];
}
m_tableDataArray = [[NSArray arrayWithArray:listDate] retain];
[addresses release];
addresses = nil;
[m_mainTable reloadData];
}
Run Code Online (Sandbox Code Playgroud)
谢谢你...
使用完毕后addressBook,需要使用以下方法释放它:
CFRelease(addressBook);
Run Code Online (Sandbox Code Playgroud)
这应该放在viewWillAppear:方法的最后.
更新:您的版本中有一些不必要的数组和步骤viewWillAppear:.我已经清理了一下并修复了潜在的内存泄漏.
注意:我实际上没有运行它,所以请仔细检查它是否正常工作.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// I assume m_tableDataArray is an instance variable. If so, if the
// view appears multiple times it will result in a leak unless we
// release pre-existing instances first.
[m_tableDataArray release], m_tableDataArray = nil;
m_tableDataArray = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *addresses = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
for (ABRecordRef record in addresses) {
NSString *firstName = (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty);
if(firstName != nil && lastName != nil){
NSString *contactFirstLast = [NSString stringWithFormat: @"%@ %@", firstName, lastName];
[m_tableDataArray addObject:contactFirstLast];
}
[firstName release];
[lastName release];
}
[addresses release], addresses = nil;
CFRelease(addressBook);
[m_mainTable reloadData];
}
Run Code Online (Sandbox Code Playgroud)