Ignas S
Ignas S

Reputation: 85

NSMutableDictionary in NSMutableArray

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

Upvotes: 2

Views: 3386

Answers (5)

PR Singh
PR Singh

Reputation: 653

Try this :

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

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

Upvotes: 0

Williham Totland
Williham Totland

Reputation: 28999

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

Upvotes: 2

trojanfoe
trojanfoe

Reputation: 122381

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

Upvotes: 0

Manu
Manu

Reputation: 4750

NSMutableDictionary *tempDicts = (NSMutableDictionary *)[yourArray objectAtIndex:yourIndex];
// Change your tempDicts 
[tempDicts setObject:@"" forKey:@""];    

and Finally

[yourArray insertOjbect:tempDicts atIndex:yourIndex];

Upvotes: 0

Antonio MG
Antonio MG

Reputation: 20410

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

Upvotes: 0

Related Questions