iPhone

2012-04-09 53 views
1

分配對象的潛在泄漏當我分析我的項目下面的代碼給我泄漏警告。有什麼辦法來解決我的內存泄漏問題?iPhone

警告:

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

謝謝進階...

+0

你必須釋放你創建/複製的任何東西。在這種情況下,ABAdressBookCreate()正在創建地址簿引用,並且您不會將其釋放到任何位置。 – EmilioPelaez 2012-04-09 05:05:12

+0

你的意思是我必須釋放這個對象? 'ABAddressBookRef addressBook = ABAddressBookCreate();' – 2012-04-09 05:06:24

+0

解釋你的代碼男人什麼是addressBook,記錄有這樣的事情。那麼有人可以幫助你 – Ayaz 2012-04-09 05:17:42

回答

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

救生員.....感謝超級回答.... – 2012-04-09 05:11:57