我知道这将是非常基本的,但我似乎无法弄清楚。
我有NSMutableArray
两个索引,每个索引都有NSMutableDictionary
几个值。我想更改一个索引中的一个值,[[anArray objectAtIndex:index] setValue:newValue forKey:someKey];
但这会更改所有索引中该键的值。我不确定发生了什么。
谢谢您的帮助。
我知道这将是非常基本的,但我似乎无法弄清楚。
我有NSMutableArray
两个索引,每个索引都有NSMutableDictionary
几个值。我想更改一个索引中的一个值,[[anArray objectAtIndex:index] setValue:newValue forKey:someKey];
但这会更改所有索引中该键的值。我不确定发生了什么。
谢谢您的帮助。
您的代码没有问题[[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";
}
在添加字典之前复制它
不要添加它 N 次,因为您将拥有一个包含 N 个指向同一个字典的指针的数组
id d1 = @{.....}.mutableCopy;
id d2 = d1.mutableCopy;
NSArray *array = @[d1,d2];
然后使用 setValueForKey 左右独立编辑键/值