简体   繁体   中英

Copying the contents of an NSMutableDictionary into another NSMutableDictionary?

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.

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM