NSMutableDictionary的深层副本

时间:2011-01-05 12:06:15

标签: iphone objective-c

如何将NSMutableDictionary的内容深层复制到另一个NSMutableDictionary?

我不想使用initWithDictionary:copyItems:方法,因为我的字典已经初始化了。

1 个答案:

答案 0 :(得分:0)

这可能有效:

- (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary

这会复制NSDictionary的密钥,而不是值。当然,如果您需要深层复制,请看一下:

@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