从通讯录iphone获取笔记时应用程序崩溃

从通讯录iphone获取笔记时应用程序崩溃,iphone,memory,crash,addressbook,Iphone,Memory,Crash,Addressbook,这是我从通讯录中获取笔记的代码 +(NSString*)getNote:(ABRecordRef)record { return ABRecordCopyValue(record, kABPersonNoteProperty); } 但在上面的实现中,我有内存泄漏。为了消除内存泄漏,我编写了以下代码 +(NSString*)getNote:(ABRecordRef)record { NSString *tempNotes = (NSString*)ABRecordCo

这是我从通讯录中获取笔记的代码

 +(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;

}
如果我写上面的代码,我的应用程序就会崩溃。出什么事了?谢谢

更新:我按如下方式调用此方法:

notes = [AddreesBook getNote:record];

其中notes是我的ivar,我将以dealloc方法释放它。

假设
记录
参数设置正确,下面应该返回一个自动释放的NSString

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

但是,我目前不明白您当前版本的
getNote
为什么不工作。

您的第一个实现违反了所有权规则:

也就是说,您使用的API调用包含“Copy”,但您将其视为自动释放的对象

鉴于您在修改后的实现中返回了一个自动释放的对象,我怀疑您没有保留返回的注释字符串。在调试器下运行时,如果应用程序在
nspopautoreeasepool()中崩溃,您将能够确定情况是否如此

一个简单的测试是将
-retain
发送到您返回的Notes对象,并查看崩溃是否消失:

NSString    *note = [ MyAddressBook getNote: abRecord ];

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

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

当它崩溃时会说什么?…谢谢你提供的信息。我会检查你的解决方案。