NSMutableArray addObject overwrites data
ios, iphone, nsmutablearray, objective-c
Solution
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];
}
Problem
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.