Search code examples
objective-cnsmutablearraynsarray

addObject NSMutableDictionary to a NSMutableArray only storing pointers not values?


I am using the following code:

NSMutableArray *data;
NSMutableDictionary *item;

item = [[NSMutableDictionary alloc] init];
data = [[NSMutableArray alloc] init];


for (int i=1; i <= 3; i++) {
    NSString *fn = [NSString stringWithFormat:@"firstname%@", [NSString stringWithFormat: @"%d", i]];
    NSString *ln = [NSString stringWithFormat:@"lastname%@", [NSString stringWithFormat: @"%d", i]];

    [item setObject:fn forKey:@"firstname"];
    [item setObject:ln forKey:@"lastname"];

    [data addObject:item];
}

NSLog(@"%@", data);

The result is not firstname1, lastname1, firstname2, lastname2, firstname3, lastname3 but:

{
    firstname = firstname3;
    lastname = lastname3;
},
    {
    firstname = firstname3;
    lastname = lastname3;
},
    {
    firstname = firstname3;
    lastname = lastname3;
}

I am missing something?


Solution

  • You need to create a new dictionary each iteration:

    NSMutableArray *data = [[NSMutableArray alloc] init];
    
    for (int i=1; i <= 3; i++) {
        NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
    
        NSString *fn = [NSString stringWithFormat:@"firstname%@", [NSString stringWithFormat: @"%d", i]];
        NSString *ln = [NSString stringWithFormat:@"lastname%@", [NSString stringWithFormat: @"%d", i]];
    
        [item setObject:fn forKey:@"firstname"];
        [item setObject:ln forKey:@"lastname"];
    
        [data addObject:item];
    }
    
    NSLog(@"%@", data);
    

    Your code was creating an array with multiple references to the same dictionary, where the last iteration was setting the value for all those dictionaries.