NSDictionary deepCopy

 

@interface NSDictionary (DeepCopy)

 

-(NSMutableDictionary *)deepCopy;

 

@end

 

@implementation NSDictionary (DeepCopy)

 

-(NSDictionary *)deepCopy {

    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithCapacity:[self count]];

    [self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull value, BOOL * _Nonnull stop) {

        id copyValue = nil;

        if ([value isKindOfClass:[NSDictionary class]]) {  //如果key对应的元素可以响应mutableDeepCopy方法(还是NSDictionary),调用mutableDeepCopy方法复制

            copyValue = [value deepCopy];

        } else if ([value isKindOfClass:[NSArray class]]) {

            copyValue = [[NSMutableArray alloc] initWithArray:value copyItems:YES];

        } else {

            copyValue = [value copy];

        }

    

        [dictionary setObject:copyValue forKey:key];

    }];

    

    return dictionary;

}

 

@end

你可能感兴趣的:(IOS)