Copying NSMutableDictionary contents to another NSMutableDictionary?

I have an NSMutableDictionary , each element of which is a different dictionary. How can I copy its contents to another NSMutableDictionary ? I tried using:

 firstDictionary = [NSMutableDictionary dictionaryWithDictionary:secondDictionary]; 

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

+6
objective-c iphone nsmutabledictionary
source share
4 answers

Check the NSDictionary method initWithDictionary: copyItems:.

It allows deep copying of elements by calling the copyWithZone: method of the item class. You will have to make sure to copy the fields yourself as part of the method.

+5
source share

You can also switch between mutable and non-mutable dictionaries with copy and mutableCopy.

 - (void) someFunc:(NSMutableDictionary *)myDict { NSDictionary *anotherDict = [myDict copy]; NSMutableDictionary *yetAnotherDict = [anotherDict mutableCopy]; } 
+10
source share

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

  • firstDictionary = [NSMutableDictionary dictionaryWithDictionary: secondDictionary];
  • [[NSDictionary alloc] initWithDictionary: secondDictionary]; // do not forget to release later
  • using a deep copy
  • using shallow copy
0
source share

Complies with the NSCopying protocol and runs copyWithZone for each object.

If NsMutableDictionary contains a different dictionary that contains a different dictionary, then you need to make copyWithZone for each dictionary at all levels.

0
source share

All Articles