I’m new to Obj-C, and I have a little problem here.
I’m trying insert the values from a temp Dictionary into an array
NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myDict setObject:[NSNumber numberWithInt:100] forKey:@"Record"];
[myDict setObject:@"www" forKey:@"Name"];
[myArray addObject:myDict];
[myDict setObject:[NSNumber numberWithInt:80] forKey:@"Record"];
[myDict setObject:@"eee" forKey:@"Name"];
[myArray addObject:myDict];
[myDict setObject:[NSNumber numberWithInt:70] forKey:@"Record"];
[myDict setObject:@"rrr" forKey:@"Name"];
[myArray addObject:myDict];
[myDict setObject:[NSNumber numberWithInt:0] forKey:@"Record"];
[myDict setObject:@"ttt" forKey:@"Name"];
[myArray addObject:myDict];
NSLog(@"myArray %@",myArray);
Regardless of the bad implementation code here (and my bad English as well :p), what I’m trying to figure out is how do I clean myDict after each insertion in myArray.
Using [myDict removeAllObjects]; after each addObject is giving me an empty array at the end.
Thanks!
Thanks for all your answers, with [myArray addObject:[[myDict copy] autorelease]]; the code works just fine.
The problem here is you’re adding the exact same mutable dictionary to the array over and over. So your array is simply a collection of references to the exact same object. Therefore it shouldn’t be surprising that every object in your array is identical to the last one.
In order to do what you want, you have two options. The first is to copy your mutable dictionary each time and add that copy to the array. You can do this by using
The other solution is to use separate dictionaries to begin with. Instead of mutating a mutable dictionary each time, you could construct a brand new NSDictionary: