setValue:forKey:设置指定索引的所有值

时间:2013-03-15 22:13:57

标签: ios nsmutablearray nsmutabledictionary

我知道这将是非常基本的,但我似乎无法弄明白。

我有一个带有两个索引的NSMutableArray,每个索引都有NSMutableDictionary个值。我想用[[anArray objectAtIndex:index] setValue:newValue forKey:someKey];更改一个索引中的一个值,但这会更改所有索引中该键的值。我不确定发生了什么。

感谢您的帮助。

2 个答案:

答案 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左右独立编辑键/值