NSUserDefaults中的Mutable对象 [英] Mutable Objects inside NSUserDefaults

查看:230
本文介绍了NSUserDefaults中的Mutable对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的数据库并放入NSUserDefaults。我的数据库是NSMutableArray,里面有字典和数组。当我从NSUSerDefaults创建NSMutableArray我不能添加任何对象到我的可变对象在我的NSMutableArray。这是我的代码:

I created a simple database and put in NSUserDefaults. My database is NSMutableArray which has dictionaries and arrays inside in it. When I create NSMutableArray from NSUSerDefaults I can't add any objects to my mutable objects inside my NSMutableArray. Here is my code:

NSMutableArray *arrayOne = [NSMutableArray arrayWithContentsOfFile:[self createEditableCopyOfIfNeededWithFileName:@"Form.plist"]];

NSUserDefaults *ayarlar = [NSUserDefaults standardUserDefaults];

[ayarlar setObject:arrayOne forKey:@"form"];

NSMutableArray *arrayTwo = [NSMutableArray arrayWithArray:[[ayarlar objectForKey:@"form"] mutableCopy]];

[[[arrayTwo objectAtIndex:0] objectForKey:@"itemlar"] addObject:@"hop"];

这里是错误:

'NSInternalInconsistencyException',reason:' - [__ NSCFArray insertObject:atIndex:]:mutating方法发送到不可变对象

工作?感谢大家。

推荐答案

NSUserDefaults不是存储数据的正确位置。首先,它应该只用于非常少量的数据,如设置。其次它总是返回不可变对象,即使你设置了可变的对象。创建第一个数组的可变副本并不有帮助,因为只有数组是可变的。

NSUserDefaults is not the right place to store your data. First of all it should only be used for very small amounts of data, such as settings. And secondly it always returns immutable objects, even if you set mutable ones. Making a mutable copy of your first array doesn’t help because only the array will be mutable. Everything that is inside that array isn’t touched by the mutableCopy method and stay immutable.

您应该使用NSPropertyListSerialization类从文件中读取和写入您的数据。在阅读时,您可以传递控制读对象的可变性的选项。在那里你将需要传递NSPropertyListMutableContainers或NSPropertyListMutableContainersAndLeaves。

You should use the NSPropertyListSerialization class to read and write your data from a file. On reading you can pass options controlling the mutability of the read objects. There you will want to pass NSPropertyListMutableContainers or NSPropertyListMutableContainersAndLeaves.

首先,所有的容器(数组和字典)都是可变的。对于后者,叶子(即NSString和NSData对象)将是可变的。

With the first all your containers (arrays and dictionaries that is) will be mutable. With the latter also the leaves (that is NSString and NSData objects) will be mutable.

根据数据集的大小,你可能应该使用真实数据库核心数据。

Depending on how big your data set can get you probably should use a real database or Core Data instead.

这篇关于NSUserDefaults中的Mutable对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆