如何将NSMutableDictionary的内容深层复制到另一个NSMutableDictionary?
我不想使用initWithDictionary:copyItems:方法,因为我的字典已经初始化了。
答案 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