ios – 如何遍历NSDictionaries和NSArrays的嵌套层次结构并将所有转换为可变副本?

前端之家收集整理的这篇文章主要介绍了ios – 如何遍历NSDictionaries和NSArrays的嵌套层次结构并将所有转换为可变副本?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个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上看过这样的东西,但现在找不到它.

原文链接:https://www.f2er.com/iOS/335518.html

猜你在找的iOS相关文章