Copying the contents of an NSMutableDictionary into another NSMutableDictionary?
Asked Answered
B

4

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.

Boyce answered 5/1, 2011 at 2:41 Comment(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?Yokum
I need a deep copy of the elements.Boyce
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.Yokum
Already posted [click here][1].. ?Hope you help... [1]: https://mcmap.net/q/1475652/-how-to-copy-nsmutabledictionary-values-into-the-another-nsmutabledictionary-in-iphoneImpact
Y
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.

Yokum answered 5/1, 2011 at 3:15 Comment(0)
P
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];
}
Pastorale answered 26/4, 2011 at 2:43 Comment(0)
Y
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.

Yokum answered 5/1, 2011 at 3:15 Comment(0)
S
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
Subsistent answered 5/1, 2011 at 2:53 Comment(0)
A
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.

Arrogate answered 5/9, 2013 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.