我有一个NSDictionary,包含许多不同类型对象的实例(NS
Arrays,NSDictionaries,NSStrings,NSNumbers等…).许多NSDictionaries和NSStrings都有自己的嵌套NSDictionaries和NSArrays.
如何从上到下遍历整个层次结构,并将NSDictionaries和NSArrays的所有实例分别转换为NSMutableDictionaries和NSMutableArrays?
是否有任何简单的“递归制作可变副本”功能我不知道?如果没有,我只需要反复循环和打字检查吗?我可以随时更换,还是重建整个层次结构?
解决方法
以下方法创建嵌套数组,字典和集的嵌套(深层)可变副本.它还可用于在层次结构内创建非集合对象的可变副本,例如字符串.
@interface NSObject (MyDeepCopy) -(id)deepMutableCopy; @end @implementation NSObject (MyDeepCopy) -(id)deepMutableCopy { if ([self isKindOfClass:[NSArray class]]) { NSArray *oldArray = (NSArray *)self; NSMutableArray *newArray = [NSMutableArray array]; for (id obj in oldArray) { [newArray addObject:[obj deepMutableCopy]]; } return newArray; } else if ([self isKindOfClass:[NSDictionary class]]) { NSDictionary *oldDict = (NSDictionary *)self; NSMutableDictionary *newDict = [NSMutableDictionary dictionary]; for (id obj in oldDict) { [newDict setObject:[oldDict[obj] deepMutableCopy] forKey:obj]; } return newDict; } else if ([self isKindOfClass:[NSSet class]]) { NSSet *oldSet = (NSSet *)self; NSMutableSet *newSet = [NSMutableSet set]; for (id obj in oldSet) { [newSet addObject:[obj deepMutableCopy]]; } return newSet; #if MAKE_MUTABLE_COPIES_OF_NONCOLLECTION_OBJECTS } else if ([self conformsToProtocol:@protocol(NSMutableCopying)]) { // e.g. NSString return [self mutableCopy]; } else if ([self conformsToProtocol:@protocol(NSCopying)]) { // e.g. NSNumber return [self copy]; #endif } else { return self; } } @end
用它就好
NSDictionary *dict = ...; NSMutableDictionary *mdict = [dict deepMutableCopy];
(不复制字典键,只复制值).
我很确定我在SO上看过这样的东西,但现在找不到它.