2012-04-09 41 views
0

這是我從AddressBook獲取Notes的代碼。從AddressBook獲取Notes時應用程序崩潰iphone

+(NSString*)getNote:(ABRecordRef)record { 

    return ABRecordCopyValue(record, kABPersonNoteProperty); 
} 

但在上面的實現中,我有內存泄漏。所以爲了消除內存泄露,我寫了下面的代碼

+(NSString*)getNote:(ABRecordRef)record { 

    NSString *tempNotes = (NSString*)ABRecordCopyValue(record, kABPersonNoteProperty); 
    NSString *notes = [NSString stringWithString:tempNotes]; 
    [tempNotes release]; 
    return notes; 

} 

如果我寫上面的代碼,我的應用程序崩潰。發生什麼事了?謝謝。

UPDATE:我把這種方法如下:

notes = [AddreesBook getNote:record]; 

其中筆記是我的伊娃&我在dealloc方法中釋放出來。

+0

崩潰時它說什麼了...... – EmilioPelaez 2012-04-09 14:37:38

回答

1

你的第一個實施違反所有權規則:

Memory Management Rules

這就是說,API調用您使用包含「複製」,但你像一個自動釋放的對象處理它。

鑑於您在修訂後的實現中返回了自動發佈的對象,我懷疑您並未保留返回的音符字符串。如果在調試器下運行,您的應用程序崩潰,您將能夠確定是否出現這種情況NSPopAutoreleasePool()

一個簡單的測試將是發送-retain的說明對象,你回來,看看是否崩潰消失:

NSString *note = [ MyAddressBook getNote: abRecord ]; 

[ note retain ]; 
/* ... use note ... */ 

/* we retained the object, we must also release it when done with it. */ 
[ note release ]; 
+0

感謝您的信息。我會檢查你的解決方案。 – iOSAppDev 2012-04-09 16:18:20

0

假設record參數設置正確,下面應該返回一個自動發佈的NSString。

+ (NSString *)getNote:(ABRecordRef)record { 
    return [(NSString *)ABRecordCopyValue(record, kABPersonNoteProperty) autorelease]; 
} 

不過,我沒有看到目前爲什麼你當前的getNote版本無法正常工作。