2012-04-09 76 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版本无法正常工作。