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.

4
  • 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? Jan 5, 2011 at 2:44
  • I need a deep copy of the elements.
    – NSExplorer
    Jan 5, 2011 at 2: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. Jan 5, 2011 at 3:07
  • Already posted [click here][1].. ?Hope you help... [1]: stackoverflow.com/a/12315674/1317127
    – Ashvin
    Sep 7, 2012 at 9:47

4 Answers 4

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];
}
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.

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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.