在NSUserDefaults保存的NSMutableArray中插入对象 [英] insert object in an NSMutableArray saved with NSUserDefaults
问题描述
我有一个NSUserDefaults保存的NSMutableArray。
这个数组是我用户可以保存的最喜欢的项目,所以当我想添加一个项目时,我需要读取数组(来自NSuserDefault)并保存在第一个空闲位置。
I have an NSMutableArray saved with NSUserDefaults. This array is my "favourite" items that the user can saves, so when i want to add one item, i need to read the array (from NSuserDefault) and save in the first free position.
我正在使用此方法在NSMutableArray中添加值
I'm using this method to add a value in the NSMutableArray
-(IBAction)save{
NSMutableArray *abc = [[NSUserDefaults standardUserDefaults] objectForKey:@"12345"];
int n = [abc count];
[abc insertObject:@"aaa" atIndex:n];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[[NSUserDefaults standardUserDefaults] setObject:abc forKey:@"12345"];
[defaults synchronize];
[abc release];
}
这笔交易是什么?
如果用户调用此方法两次,则应用程序第二次与此日志崩溃:
what's the deal? That if the user call this method two times, the second time the app crashes with this log:
* 由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:' - [__ NSCFArray insertObject:atIndex:]:发送到不可变对象的mutating方法'
* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'
为什么?
和为什么只是第二次?
第一次工作正常!
why? and why just the second time? The first time works fine!
推荐答案
NSUserDefaults
总是返回不可变对象,即使原始对象是可变的。它位于 objectForKey
的文档中:
NSUserDefaults
always returns immutable objects, even if the original object was mutable. It's in the documentation for objectForKey
:
返回的对象是不可变的,即使您最初设置的值是可变的。
The returned object is immutable, even if the value you originally set was mutable.
您需要在修改之前创建返回对象的副本,使用 [NSMutableArray arrayWithArray:]
You will need to create a copy of the returned object before you modify it, using [NSMutableArray arrayWithArray:]
也可能最好使用 arrayForKey
如果您正在检索数组,则 NSUserDefaults
的方法。文档: https://developer.apple.com/documentation/foundation/userdefaults
Probably also best to use the arrayForKey
method of NSUserDefaults
if you're retrieving an array. Docs here: https://developer.apple.com/documentation/foundation/userdefaults
这篇关于在NSUserDefaults保存的NSMutableArray中插入对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!