开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜