0

这是我从地址簿获取笔记的代码。

 +(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 方法中释放它。

4

2 回答 2

1

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

内存管理规则

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

Given that you're returning an autoreleased object in your revised implementation, I suspect you're not retaining your returned note string. You'll be able to tell for sure if this is the case if when running under a debugger your app crashes in NSPopAutoreleasePool().

A simple test would be to send -retain to the note object you get back and see if the crash goes away:

NSString    *note = [ MyAddressBook getNote: abRecord ];

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

/* we retained the object, we must also release it when done with it. */
[ note release ];
于 2012-04-09T14:56:57.337 回答
0

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

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

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

于 2012-04-09T14:52:20.287 回答