1

当我分析我的项目时,下面的代码给了我泄漏警告。有什么办法可以解决我的内存泄漏问题吗?

警告 :

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

感谢您的建议...

4

1 回答 1

6

完成使用后,addressBook您需要使用以下命令释放它:

CFRelease(addressBook);

这可能应该放在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];
}
于 2012-04-09T05:10:35.017 回答