2013-10-21 71 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 
    } 
相關問題