Deep copy of NSMutableDictionary
How can one deep-copy the contents of an NSMutableDictionary to another NSMutableDictionary?
I do not want to use initWithDictionary:copyItems: method as my di开发者_运维知识库ctionaries are already initialized.
This might work:
- (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary
This copies the Keys, But not the values, of an NSDictionary
. Of course, If you need a deep copy, take a look at this:
@interface NSDictionary(rross)
- (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary copyItems:(BOOL) copyItems;
@end
@implementation NSDictionary(rross)
- (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary copyItems:(BOOL) copyItems
{
if (copyItems)
{
// get the keys
NSArray *oldKeys = [otherDictionary allKeys];
for (int i = 0; i < oldKeys.count; i++)
{
// add all the new key / value pairs
id key = [oldKeys objectAtIndex:i];
[self setObject:[[[otherDictionary objectForKey:key] copy] autorelease] forKey:[[key copy] autorelease]];
}
}
else
{
[self addEntriesFromOtherDictionary:otherDictionary];
}
}
@end
精彩评论