问题
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:
- firstDictionary = [NSMutableDictionary dictionaryWithDictionary:secondDictionary];
- [[NSDictionary alloc] initWithDictionary:secondDictionary]; //don't forget to release later
- using deep copy
- 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