2
votes

I have NSMutableArray populated with NSMutableDictionary objects, how can I retrieve let's say second item in NSMutableArray and change that dictionary.

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

So i need to access NSDictionary by Key and change Key's value. Thank you

5

5 Answers

2
votes

Objects in an array are, as you have discovered, accessed using the -objectAtIndex: method on NSArray.

Similarly, objects in a dictionary are accesses using -objectForKey: on NSDictionary.

To do what you want, just stack the accesses as with any other call, like so:

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

Take note, the indexing on NSArray starts at 0, not 1.

To change values, the same principle applies:

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

If you want to replace a value in a NSMutableDictionary store in an NSMutableArray, use this code:

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

and Finally

[yourArray insertOjbect:tempDicts atIndex:yourIndex];
0
votes

Assuming the array is an instance variable (called _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];
}

To use:

[self setObject:@"foobar" forKey:@"title" atIndex:2];
0
votes

Try this :

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

       //you can access dictionay here and set the value 
    }