我知道这将是非常基本的,但我似乎无法弄明白。
我有一个带有两个索引的NSMutableArray
,每个索引都有NSMutableDictionary
个值。我想用[[anArray objectAtIndex:index] setValue:newValue forKey:someKey];
更改一个索引中的一个值,但这会更改所有索引中该键的值。我不确定发生了什么。
感谢您的帮助。
答案 0 :(得分:1)
您的代码[[anArray objectAtIndex:index] setValue:newValue forKey:someKey];
您应该像这样添加NSMutableDictionary
NSMutableArray *myArray = [[NSMutableArray alloc] init];
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"dict1value1", @"key1", @"dict1value2", @"key2", nil];
[myArray addObject:[dict1 copy]];
[myArray addObject:dict1];
[[myArray objectAtIndex:1] setValue:@"NEW VALUE" forKey:@"key2"];
NSLog(@"%@",[myArray objectAtIndex:0]);
NSLog(@"%@",[myArray objectAtIndex:1]);
或
NSMutableArray *myArray = [[NSMutableArray alloc] init];
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"dict1value1", @"key1", @"dict1value2", @"key2", nil];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"dict2value1", @"key1", @"dict2value2", @"key2", nil];
[myArray addObject:dict1];
[myArray addObject:dict2];
[[myArray objectAtIndex:1] setValue:@"NEW VALUE" forKey:@"key2"];
NSLog(@"%@",[myArray objectAtIndex:0]);
NSLog(@"%@",[myArray objectAtIndex:1]);
<强>输出强>
{
key1 = dict1value1;
key2 = dict1value2;
}
{
key1 = dict1value1;
key2 = "NEW VALUE";
}
答案 1 :(得分:0)
在添加词典
之前复制它不要添加N次,因为你将拥有一个带有指向同一字典的N个指针的数组
id d1 = @{.....}.mutableCopy;
id d2 = d1.mutableCopy;
NSArray *array = @[d1,d2];
然后使用setValueForKey左右独立编辑键/值