iOS:NSUserDefault 用于 UIImage 数组
我想存储 UIImage 数组,我这样做:
//in didFinishLaunchingWithOption
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:@"theKey"];
if (data == NULL) arrayImage = [[NSMutableArray alloc] init];
else {arrayImage = [[NSMutableArray alloc] init]; arrayImage = [NSKeyedUnarchiver unarchiveObjectWithData:data];}
NSLog(@"arrayImage:%@", arrayImage);
//and in applicationDidEnterBackground
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arrayImage];
[defaults setObject:data forKey:@"theKey"];
NSLog(@"arrayImage:%@", arrayImage);
当应用程序在 nslog 中的 didFinishLaunchingWithOption 中运行时,我看到数组中的所有对象,但是当我使用它时,我发生崩溃,显示“[__NSArrayM count]:消息发送到已释放实例”为什么?
I want to store an array of UIImage and I do this:
//in didFinishLaunchingWithOption
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:@"theKey"];
if (data == NULL) arrayImage = [[NSMutableArray alloc] init];
else {arrayImage = [[NSMutableArray alloc] init]; arrayImage = [NSKeyedUnarchiver unarchiveObjectWithData:data];}
NSLog(@"arrayImage:%@", arrayImage);
//and in applicationDidEnterBackground
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arrayImage];
[defaults setObject:data forKey:@"theKey"];
NSLog(@"arrayImage:%@", arrayImage);
when app run in didFinishLaunchingWithOption in nslog I see all object in my array, but when I use it, I have a crash that say "[__NSArrayM count]: message sent to deallocated instance" why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不完全确定,但我认为
为您提供一个自动释放的对象,因此您可以保留它。我认为它会给你一个不可变的对象,所以当你尝试从中添加或删除对象时,你会得到一个错误(我对此不确定,但我想我曾经遇到过这种情况.. .)
我会重写你的代码的某些部分:
I'm not completely sure, but I think that
gives you an autoreleased object, so you may retain it. And I think it will give you a non-mutable object, so when you will try to add or remove objects from it you will get an error (I'm no sure about this, but I think I once was in this situation...)
I would rewrite some part of your code:
我假设你没有使用 ARC。问题在于:
在
HERE
处,您将arrayImage
中的值替换为键控解档器的新实例。您之前init
的值丢失了(事实上,泄漏了)。来自解档器的值是一个自动释放的对象,因此当池耗尽时将被释放。这是在进行applicationDidEnterBackground
调用之前。正确的解决方案是保留解档器中的值。即:
I assume you're not using ARC. The problem is in:
At
HERE
, you replace the value inarrayImage
with a new instance for the keyed unarchiver. The value youinit
'd just previously is lost (in fact, leaked). The value from the unarchiver is an autoreleased object, so will be released when the pool is drained. This is before theapplicationDidEnterBackground
call is made.The correct solution is to retain the value from the unarchiver. Viz: