deep mutable copy of a NSMutableDictionary

前端 未结 8 1905
醉话见心
醉话见心 2020-11-30 00:55

I am trying to create a deep-copy of a NSMutableDictionary and assign it to another NSMutableDictionary. The dictionary contains a bunch of arrays, each array containing nam

8条回答
  •  無奈伤痛
    2020-11-30 01:15

    Useful answers here, but CFPropertyListCreateDeepCopy doesn't handle [NSNull null] in the data, which is pretty normal with JSON decoded data, for example.

    I'm using this category:

        #import 
    
        @interface NSObject (ATMutableDeepCopy)
        - (id)mutableDeepCopy;
        @end
    

    Implementation (feel free to alter / extend):

        @implementation NSObject (ATMutableDeepCopy)
    
        - (id)mutableDeepCopy
        {
            return [self copy];
        }
    
        @end
    
        #pragma mark - NSDictionary
    
        @implementation NSDictionary (ATMutableDeepCopy)
    
        - (id)mutableDeepCopy
        {
            return [NSMutableDictionary dictionaryWithObjects:self.allValues.mutableDeepCopy
                                                      forKeys:self.allKeys.mutableDeepCopy];
        }
    
        @end
    
        #pragma mark - NSArray
    
        @implementation NSArray (ATMutableDeepCopy)
    
        - (id)mutableDeepCopy
        {
            NSMutableArray *const mutableDeepCopy = [NSMutableArray new];
            for (id object in self) {
                [mutableDeepCopy addObject:[object mutableDeepCopy]];
            }
    
            return mutableDeepCopy;
        }
    
        @end
    
        #pragma mark - NSNull
    
        @implementation NSNull (ATMutableDeepCopy)
    
        - (id)mutableDeepCopy
        {
            return self;
        }
    
        @end
    

    Example extensions – strings are left as normal copies. You could override this if you want to be able to in place edit them. I only needed to monkey with a deep down dictionary for some testing, so I've not implemented that.

提交回复
热议问题