2

我已经NSMutableArray填充了NSMutableDictionary对象,我该如何检索让我们说第二项NSMutableArray并更改该字典。

NSMutableArray *tempArr = [[NSMutableArray alloc]init];
NSMutableDictionary *al = [[NSMutableDictionary alloc]init];

for(int i=0; i<[theArray count]; i++) {
    id object = [theArray objectAtIndex: i];
    id object2 = @"0";
    [al  setObject:object forKey:@"titles"];
    [al setObject:object2 forKey:@"levels"];
    [tempArr addObject:al];
}


NSLog(@"fubar %@", [tempArr objectAtIndex:2]);

所以我需要通过 Key 访问 NSDictionary 并更改 Key 的值。谢谢

4

5 回答 5

2

正如您所发现的,数组中的对象是使用-objectAtIndex:on 方法访问的NSArray

类似地,字典中的对象是使用-objectForKey:on的访问NSDictionary

要做你想做的事,只需像任何其他调用一样堆叠访问,如下所示:

NSLog(@"fubar %@", [[tempArr objectAtIndex:2] objectForKey:@"titles"]);

请注意,索引NSArray从 0 开始,而不是 1。

要更改值,同样的原则适用:

[[tmpArr objectAtIndex:2] setObject:titlesArray forKey:@"titles"];
于 2013-10-21T09:15:34.883 回答
0

如果要替换 中的NSMutableDictionary存储中的值NSMutableArray,请使用以下代码:

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",nil],[NSMutableDictionary dictionaryWithObjectsAndKeys:@"value2",@"key2",nil], nil];

//Edit second value
NSMutableDictionary *dict = (NSMutableDictionary *)[array objectAtIndex:1];
[dict setObject:@"value3" forKey:@"key2"];
于 2013-10-21T09:14:02.373 回答
0
NSMutableDictionary *tempDicts = (NSMutableDictionary *)[yourArray objectAtIndex:yourIndex];
// Change your tempDicts 
[tempDicts setObject:@"" forKey:@""];    

最后

[yourArray insertOjbect:tempDicts atIndex:yourIndex];
于 2013-10-21T09:14:45.770 回答
0

假设数组是一个实例变量(称为_array):

- (void)setObject:(id)value
           forKey:(id)key
          atIndex:(NSInteger)index {
    if (index >= [_array count]) {
        NSLog(@"Index %ld out-of-range", index);
        return;
    }
    NSMutableDictionary *dict = [_array objectAtIndex:index];
    [dict setObject:value forKey:key];
}

要使用:

[self setObject:@"foobar" forKey:@"title" atIndex:2];
于 2013-10-21T09:14:56.020 回答
0

尝试这个 :

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for(dict in tempArr)
    {

       //you can access dictionay here and set the value 
    }
于 2013-10-21T09:23:25.387 回答