【发布时间】:2015-07-11 10:17:06
【问题描述】:
我在 NSMutableDictionary 中有一个数组,我想向其中添加对象。使用我目前的方法,我得到一个错误,说数组是不可变的。
我认为问题出在我将字典保存到 NSUserDefaults 时。我正在检索它是 NSDictionary,但同时我正在创建一个新的 NSMutableDictionary 内容。
但是,数组似乎是不可变的。如何替换字典中的数组?
我的字典是这样的:
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithInt:0], nil];
NSDictionary *dict = @{
@"firstKey": @{
@"theArray":array,
}
};
NSMutableDictionary *mutDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
我正在尝试添加这样的对象:
[[[mutDict objectForKey:@"firstKey"] objectForKey:@"theArray"] addObject:[NSNumber numberWithInt:5]];
我可以在将对象保存到NSUserDefaults之前将对象添加到mutDict内的数组中
从 NSUserDefaults 加载字典后尝试添加到字典中的数组时收到的错误消息:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'
【问题讨论】:
-
这里有两个字典。键“theArray”来自第二个字典。您想向第二个字典添加更多键/值,对吗?
-
我想在“数组”中添加更多值,即向键 @“theArray”的值添加更多对象。我说得通吗?
-
好的,通过这种方式,您可以替换具有键“theArray”的整个数组。例如。使用数组初始化可变数组(您的“theArray”)添加项目并将值设置为字典键“theArray”
-
好的,你能给我一个可以替换数组的例子吗?我需要删除旧的然后添加新的吗?非常感谢。
-
您的代码运行良好,它向数组
2015-07-11 11:40:05.599 TestC[422:4891] { firstKey = { theArray = ( 0, 5 ); }; }添加了一个新数字5
标签: ios objective-c nsarray nsdictionary nsuserdefaults