Copying the contents of an NSMutableDictionary into another NSMutableDictionary?

三世轮回 提交于 2019-12-07 04:04:17

问题


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.


回答1:


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.




回答2:


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



回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/4600386/copying-the-contents-of-an-nsmutabledictionary-into-another-nsmutabledictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!