views:

649

answers:

1

Hi Is it possible to take 2 NSDictionaries and populate 1 NSMutableArray? So lets say I have this situation:

dict1 = key/value of: id/firstname

dict2 = key/value of: id/lastname

(These are populated from a database query to the server)

Now, I want to combine the dictionaries into an NSMutableArray of "user" objects. the user object has these variables, mapping to the 2 NSDict objects above. So: id, firstname, lastname (everything is an NSString)

I tried various things.

The problem is the following, when I extract the NSDictionary key/values (using NSEnumerator - but also tried with a slower for loop) and add the resulting object into the mutablearray, the values of the objects inside the array get initialized to the same object for all preceeding values. Example:

id:1 - firstname: John - lastname: Brown
id:2 - firstname: Mike - lastname: Blue
id:3 - firstname: Mary - lastname: White

By the time I am done with the enumeration, and reach the end of the loop, my array looks like this (all objects are identical)

id:3 - firstname: Mary - lastname: White
id:3 - firstname: Mary - lastname: White
id:3 - firstname: Mary - lastname: White

Please help! Any advice, even a pointer (no pun intended) would be much appreciated.

Cheers.

+1  A: 

Not sure what your issue is, a code snippet might help, but here's how I would go about it:

for (NSString *key in [dict1 allKeys]) {
  User *u = [[User alloc] initWithId:key
                           firstName:[dict1 objectForKey:key]
                            lastName:[dict2 objectForKey:key]];
  [users addObject:u];
  [u release];
}

I wouldn't use the NSEnumerator for the objects themselves because they are in no guaranteed order.

If that's already what you're doing, you may need to look at something wonky with your User init method. Are you, in fact, using the same object over and over?

Ed Marty
Thank you Ed - it worked like a charm! I was overcomplicating the situation by not leveraging my init method. Thanks again.
Ferris
You should mark his answer as accepted if it worked for your problem.
Jonah