我是ios编程的新手,上个月刚开始学习这个。
过去两天我遇到了一个问题。 我无法弄明白如何自己解决这个问题。
所以,我想请你帮我解决这个问题!
这是我得到的错误。
[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
我了解到我收到此错误,因为我从NSUserDefaults获取的对象始终是不可变的。
所以,我mutableCopy我要添加新对象的数组。
NSMutableArray *temporaryArray = [users[1][@"users"] mutableCopy];
[temporaryArray addObject:myData];
users[1][@"users"] = temporaryArray;
但是,在上面的第三行,当然会导致同样的错误。
我知道它导致此错误的原因,但我不知道如何编码来解决此问题。我认为解决方案非常简单和基本,但我无法弄清楚如何。
如果有人帮我解决这个问题我很感激!!
非常感谢你!
- (void)saveData
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *users = [userDefaults objectForKey:@"users"];
NSDictionary *myData = @{@"name":@"test", @"birthdate":@"1981-01-01", @"sex":@"male"};
NSMutableArray *temporaryArray = [users[1][@"users"] mutableCopy];
[temporaryArray addObject:myData];
users[1][@"users"] = temporaryArray;
[userDefaults setObject:users forKey:@"users"];
[userDefaults synchronize];
[self.target performSelector:self.action withObject:@"test.png"];
[self dismissViewControllerAnimated:YES completion:nil];
}
“user”数组的结构。
(
{
label = "\U81ea\U5206";
users = (
{
birthdate = "2013-10-12";
name = Test;
sex = "\U7537\U6027";
}
);
},
{
label = "Family(\U5bb6\U65cf)";
users = (
);
},
{
label = "Friends(\U53cb\U9054)";
users = (
);
}
)
答案 0 :(得分:1)
您获得的数组users
不是可变副本:
NSMutableArray *users = [userDefaults objectForKey:@"users"];
您对同一个数组使用temporaryArray
,temporary
和testArray
?错字?我想你想要的是:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *users = [[userDefaults objectForKey:@"users"] mutableCopy];
NSDictionary *myData = @{@"name":@"test", @"birthdate":@"1981-01-01", @"sex":@"male"};
NSMutableArray *usersNested = [users[1][@"users"] mutableCopy];
[usersNested addObject:myData];
[users replaceObjectAtIndex:1 withObject:usersNested];
[userDefaults setObject:users forKey:@"users"];
[userDefaults synchronize];
答案 1 :(得分:1)
您正在尝试改变不可变字典,该字典是数组的对象之一。
尝试以下方法:
- (void)saveData
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *users = [[userDefaults objectForKey:@"users"] mutableCopy];
NSDictionary *myData = @{@"name":@"test", @"birthdate":@"1981-01-01", @"sex":@"male"};
//Create a mutable copy of the dictionary object at index 1.
NSMutableDictionary* mutableUsers = [users[1] mutableCopy]
NSMutableArray *temporaryArray = [mutableUsers[@"users"] mutableCopy];
[temporaryArray addObject:myData];
mutableUsers[@"users"] = [temporaryArray copy];
//Replace the dictionary with an immutable copy of the new dictionary.
users[1] = [mutableUsers copy];
[userDefaults setObject:users forKey:@"users"];
[userDefaults synchronize];
[self.target performSelector:self.action withObject:@"test.png"];
[self dismissViewControllerAnimated:YES completion:nil];
}