简体   繁体   English

将NSMutableDictionary的内容复制到另一个NSMutableDictionary中?

[英]Copying the contents of an NSMutableDictionary into another NSMutableDictionary?

I have an NSMutableDictionary each element of which is another dictionary. 我有一个NSMutableDictionary ,其中每个元素都是另一个字典。 What is the best way I can copy its contents into another NSMutableDictionary ? 我可以将其内容复制到另一个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. 您还可以使用copy和mutableCopy在可变字典和非可变字典之间跳转。

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

Check the NSDictionary initWithDictionary:copyItems: method. 检查NSDictionary initWithDictionary:copyItems:方法。

It it enables deep copying of elements thru calling copyWithZone: method of item's class. 它通过调用copyWithZone:item类的方法来实现元素的深度复制。 You will have to take care of copying the fields yourself within the method. 您必须自己在方法中自己复制字段。

Conform to NSCopying Protocol and do copyWithZone on every object. 符合NSCopying协议并对每个对象执行copyWithZone。

If NsMutableDictionary contains another dictionary, which contains another dictionary,, then you need to do copyWithZone on each dictionary at all levels. 如果NsMutableDictionary包含另一个包含另一个字典的字典,那么你需要在所有级别的每个字典上执行copyWithZone。

What do you mean by "best"? “最好的”是什么意思?
Anyway, I listed some ways here: 无论如何,我在这里列举了一些方法:

  1. firstDictionary = [NSMutableDictionary dictionaryWithDictionary:secondDictionary]; firstDictionary = [NSMutableDictionary dictionaryWithDictionary:secondDictionary];
  2. [[NSDictionary alloc] initWithDictionary:secondDictionary]; [[NSDictionary alloc] initWithDictionary:secondDictionary]; //don't forget to release later //不要忘记稍后发布
  3. using deep copy 使用深层复制
  4. using shallow copy 使用浅拷贝

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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