对象的潜在泄漏的iphone分配(Potential leak of an object alloc

2019-10-16 13:54发布

当我分析我的项目下面的代码给我泄漏报警。 有没有什么办法来解决我的内存泄露问题?

警告 :

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

谢谢进阶...

Answer 1:

一旦你已经使用完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];
}


文章来源: Potential leak of an object allocated in iphone