问题描述
当我分析我的项目时,以下代码会给我泄漏警告.有什么办法可以解决我的内存泄漏问题?
when i am analyze my project following code gives me leakage warning. is there any way to solve my memory leakage problem ?
警告:
Potential leak of an object allocated on line 38 and stored into 'addressBook'
下面是我的代码.
- (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];
}
感谢adv ...
推荐答案
使用完addressBook
后,您需要使用以下命令将其释放:
Once you have finished using addressBook
you need to release it using:
CFRelease(addressBook);
这可能应该放在viewWillAppear:
方法的末尾.
This should probably be placed at the end of your viewWillAppear:
method.
已更新:您的viewWillAppear:
版本中有一些不必要的数组和步骤.我已经对其进行了一些清理,并修复了潜在的内存泄漏.
Updated: There are a few unnecessary arrays and steps in your version of viewWillAppear:
. I have cleaned it up a bit and fixed a potential memory leak.
注意:我实际上并没有运行它,因此请仔细检查它是否可以正常工作.
Note: I haven't actually run this so double-check that it works correctly.
- (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];
}
这篇关于iPhone中分配的对象的潜在泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!