iOSDev
iOSDev

Reputation: 3617

NSMutableArray addObject overwrites data

I am adding an object "m" to NSMutableArray as follows:

    [m setObject:a forKey:@"a"];
    [m setObject:b forKey:@"b"];
    [m setObject:c forKey:@"c"];
    [m setObject:d forKey:@"d"];

    [myArray addObject:m];

    [m release];

For one object it works fine, but when another objects are added, same values are repeated for all the objects in myArray.

How to avoid this?

Please help.

Thanks.

Upvotes: 2

Views: 2344

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You need to create a separate instance of NSMUtablearray each time you populate and insert it, otherwise you keep re-using the same instance, so only the last state of it appears in each position of the array.

NSMutableArray *myArray = [NSMutableArray array];
for (int i = 0 ; i != 10 ; i++) {
    NSMutableDictionary *m = [NSMutableDictionary dictionary];
    // Presumably, this part is done differently on each iteration
    [m setObject:a forKey:@"a"];
    [m setObject:b forKey:@"b"];
    [m setObject:c forKey:@"c"];
    [m setObject:d forKey:@"d"];
    [myArray addObject:m];
}

Upvotes: 11

CReaTuS
CReaTuS

Reputation: 2595

Try this:

 NSMutableDictionary* m = [NSMutableDictionary dictionary];
[m setObject:@"1" forKey:@"a"];
[m setObject:@"2" forKey:@"b"];
[m setObject:@"3" forKey:@"c"];
[m setObject:@"4" forKey:@"d"];

NSMutableArray* myArray = [NSMutableArray array];
[myArray addObject:m];

NSLog(@"%@", m);
NSLog(@"%@", myArray);

Upvotes: 1

Related Questions