7

I have an NSMutableDictionary each element of which is another dictionary. What is the best way I can copy its contents into another NSMutableDictionary? I've tried using:

firstDictionary = [NSMutableDictionary dictionaryWithDictionary:secondDictionary];

However not sure if this is the best way to do it.

Girish
  • 4,692
  • 4
  • 35
  • 55
NSExplorer
  • 11,849
  • 12
  • 49
  • 62
  • As minimum, it's the most descriptive. Why do you think it's not the best? Do you need a deep or shallow copy of elements? – Schultz9999 Jan 05 '11 at 02:44
  • I need a deep copy of the elements. – NSExplorer Jan 05 '11 at 02:46
  • Deep copy means you have to make a copy of every single field of each element (which in turn means deep copy of fields' fields and so on). That functionality is not provided by any collection class. You have to take care of that yourself. – Schultz9999 Jan 05 '11 at 03:07
  • Already posted [click here][1].. ?Hope you help... [1]: http://stackoverflow.com/a/12315674/1317127 – Ashvin Sep 07 '12 at 09:47

4 Answers4

17

You can also jump between mutable and non-mutable dictionaries using copy and mutableCopy.

- (void) someFunc:(NSMutableDictionary *)myDict {
    NSDictionary *anotherDict = [myDict copy];
    NSMutableDictionary *yetAnotherDict = [anotherDict mutableCopy];
}
Jay Imerman
  • 4,475
  • 6
  • 40
  • 55
6

Check the NSDictionary initWithDictionary:copyItems: method.

It it enables deep copying of elements thru calling copyWithZone: method of item's class. You will have to take care of copying the fields yourself within the method.

Spartacus9
  • 164
  • 2
  • 18
Schultz9999
  • 8,717
  • 8
  • 48
  • 87
0

Conform to NSCopying Protocol and do copyWithZone on every object.

If NsMutableDictionary contains another dictionary, which contains another dictionary,, then you need to do copyWithZone on each dictionary at all levels.

0

What do you mean by "best"?
Anyway, I listed some ways here:

  1. firstDictionary = [NSMutableDictionary dictionaryWithDictionary:secondDictionary];
  2. [[NSDictionary alloc] initWithDictionary:secondDictionary]; //don't forget to release later
  3. using deep copy
  4. using shallow copy
Neilvert Noval
  • 1,655
  • 2
  • 15
  • 21