2013-10-21 49 views
2

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

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]); 

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

回答

2

对象是,因为你已经发现,使用-objectAtIndex:方法上NSArray访问。

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

做你想做什么,只是堆的访问与任何其他呼叫,像这样:

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

。注意到,在0上NSArray开始索引,而不是1

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

[[tmpArr objectAtIndex:2] setObject:titlesArray forKey:@"titles"]; 
+0

如何在数组中找到的字典示例中找到“2”的索引? – Ron

+0

@Ron我不太确定你的意思; '-indexOfObject:',也许? –

+0

我有一个特定的键和值的字典。这个字典在一个NSMutableArray里面。我想用特定的键更新字典,并且此字典位于数组中的某个索引处。我想找到这个字典对象的索引。目前,我的字典位于索引0,我的索引路径是1,所以'indexpath.row'不能帮助我。这对你有意义吗?谢谢 – Ron

0

如果你想在一个NSMutableArray替换一个NSMutableDictionary存储值,使用此代码:

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"]; 
0
NSMutableDictionary *tempDicts = (NSMutableDictionary *)[yourArray objectAtIndex:yourIndex]; 
// Change your tempDicts 
[tempDicts setObject:@"" forKey:@""];  

和最后

[yourArray insertOjbect:tempDicts atIndex:yourIndex]; 
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]; 
0

试试这个:

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

     //you can access dictionay here and set the value 
    } 
相关问题