NSKeyedUnarchiver 在解码数组后崩溃

发布于 2024-09-17 12:53:23 字数 836 浏览 2 评论 0原文

我有一个非常令人沮丧的问题。
当我在解码 NSArray 后尝试释放 NSKeyedUnarchiver 对象时,出现“EXC_BAD_ACCESS”错误。
但是当我不释放它或解码其他对象(例如 NSString)时,一切都会顺利。
我不明白......对我来说,它看起来像“decodeObjectForKey”方法改变了“解码器”对象中的某些内容(但并非总是如此?!)。在调试器中,调用此方法后唯一发生变化的变量是“_replacementMap”。但我不知道如何修复这个错误。
我希望你能帮助我。
这是示例代码:

+ (NSArray *)decodeArticles {
NSString *archivePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"Articles.archive"];
NSData *decoderData = [[NSData alloc] initWithContentsOfFile:archivePath];
NSKeyedUnarchiver *decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:decoderData];

NSArray *savedArticles = [[decoder decodeObjectForKey:@"articles"] copy];
if (!savedArticles) {
    savedArticles = [[NSArray alloc] init];
}

[decoder finishDecoding];
//[decoder release];

return savedArticles;

}

I have very frustrating problem.
When I try to release NSKeyedUnarchiver object after decoding an NSArray, "EXC_BAD_ACCESS" error occurs.
But when I don't release it or decode other object (e.g. NSString) everything go well.
I don't understand it... For me, it looks like "decodeObjectForKey" method changes something in "decoder" object (but not allways?!). And in debugger, the only variable which changes after calling this method is "_replacementMap". But I have no idea how to fix this bug.
I hope you can help me.
Here is sample code:

+ (NSArray *)decodeArticles {
NSString *archivePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"Articles.archive"];
NSData *decoderData = [[NSData alloc] initWithContentsOfFile:archivePath];
NSKeyedUnarchiver *decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:decoderData];

NSArray *savedArticles = [[decoder decodeObjectForKey:@"articles"] copy];
if (!savedArticles) {
    savedArticles = [[NSArray alloc] init];
}

[decoder finishDecoding];
//[decoder release];

return savedArticles;

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

留一抹残留的笑 2024-09-24 12:53:25

还有一些事情:
1.需要释放decoderData;初始化解码器后应该能够执行此操作;认为静态分析器应该指出这一点。
2.尝试移动[decoder finishDecoding]; [解码器发布];在 if 块之前
3. 约定可能会建议您返回一个自动释放的对象,因为实现是一个类方法。您可以考虑向该方法添加路径参数。
4.将副本更改为自动发布。
5.数组中的对象肯定会影响编码过程。这可以解释为什么某些“标准”对象以您期望的方式进行编码和解码。

A few more things:
1. need to release the decoderData; should be able to do this after initializing decoder; think the static analyzer should point this out.
2. try moving [decoder finishDecoding]; [decoder release]; before the if block
3. convention might suggest you return an autoreleased object since the implementation is a class method. you might consider adding a path argument to the method.
4. change copy to autorelease.
5. the objects in your array can definitely affect the encoding process. which may explain why some "standard" objects encode and decode the way you would expect.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文