Deep copying an NSArray

82,166

Solution 1

As the Apple documentation about deep copies explicitly states:

If you only need a one-level-deep copy:

NSMutableArray *newArray = [[NSMutableArray alloc] 
                             initWithArray:oldArray copyItems:YES];

The above code creates a new array whose members are shallow copies of the members of the old array.

Note that if you need to deeply copy an entire nested data structure — what the linked Apple docs call a true deep copy — then this approach will not suffice. Please see the other answers here for that.

Solution 2

The only way I know to easily do this is to archive and then immediately unarchive your array. It feels like a bit of a hack, but is actually explicitly suggested in the Apple Documentation on copying collections, which states:

If you need a true deep copy, such as when you have an array of arrays, you can archive and then unarchive the collection, provided the contents all conform to the NSCoding protocol. An example of this technique is shown in Listing 3.

Listing 3 A true deep copy

NSArray* trueDeepCopyArray = [NSKeyedUnarchiver unarchiveObjectWithData:
          [NSKeyedArchiver archivedDataWithRootObject:oldArray]];

The catch is that your object must support the NSCoding interface, since this will be used to store/load the data.

Swift 2 Version:

let trueDeepCopyArray = NSKeyedUnarchiver.unarchiveObjectWithData(
    NSKeyedArchiver.archivedDataWithRootObject(oldArray))

Solution 3

Copy by default gives a shallow copy

That is because calling copy is the same as copyWithZone:NULL also known as copying with the default zone. The copy call does not result in a deep copy. In most cases it would give you a shallow copy, but in any case it depends on the class. For a thorough discussion I recommend the Collections Programming Topics on the Apple Developer site.

initWithArray:CopyItems: gives a one-level deep copy

NSArray *deepCopyArray = [[NSArray alloc] initWithArray:someArray copyItems:YES];

NSCoding is the Apple recommended way to provide a deep copy

For a true deep copy (Array of Arrays) you will need NSCoding and archive/unarchive the object:

NSArray *trueDeepCopyArray = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:oldArray]];

Solution 4

For Dictonary

NSMutableDictionary *newCopyDict = (NSMutableDictionary *)CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)objDict, kCFPropertyListMutableContainers);

For Array

NSMutableArray *myMutableArray = (NSMutableArray *)CFPropertyListCreateDeepCopy(NULL, arrData, kCFPropertyListMutableContainersAndLeaves);

Solution 5

No, there isn't something built into the frameworks for this. Cocoa collections support shallow copies (with the copy or the arrayWithArray: methods) but don't even talk about a deep copy concept.

This is because "deep copy" starts to become difficult to define as the contents of your collections start including your own custom objects. Does "deep copy" mean every object in the object graph is a unique reference relative to every object in the original object graph?

If there was some hypothetical NSDeepCopying protocol, you could set this up and make decisions in all of your objects, but unfortunately there isn't. If you controlled most of the objects in your graph, you could create this protocol yourself and implement it, but you'd need to add a category to the Foundation classes as necessary.

@AndrewGrant's answer suggesting the use of keyed archiving/unarchiving is a nonperformant but correct and clean way of achieving this for arbitrary objects. This book even goes so far so suggest adding a category to all objects that does exactly that to support deep copying.

Share:
82,166
ivanTheTerrible
Author by

ivanTheTerrible

Updated on July 24, 2022

Comments

  • ivanTheTerrible
    ivanTheTerrible almost 2 years

    Is there any built-in function that allows me to deep copy an NSMutableArray?

    I looked around, some people say [aMutableArray copyWithZone:nil] works as deep copy. But I tried and it seems to be a shallow copy.

    Right now I am manually doing the copy with a for loop:

    //deep copy a 9*9 mutable array to a passed-in reference array
    
    -deepMuCopy : (NSMutableArray*) array 
        toNewArray : (NSMutableArray*) arrayNew {
    
        [arrayNew removeAllObjects];//ensure it's clean
    
        for (int y = 0; y<9; y++) {
            [arrayNew addObject:[NSMutableArray new]];
            for (int x = 0; x<9; x++) {
                [[arrayNew objectAtIndex:y] addObject:[NSMutableArray new]];
    
                NSMutableArray *aDomain = [[array objectAtIndex:y] objectAtIndex:x];
                for (int i = 0; i<[aDomain count]; i++) {
    
                    //copy object by object
                    NSNumber* n = [NSNumber numberWithInt:[[aDomain objectAtIndex:i] intValue]];
                    [[[arrayNew objectAtIndex:y] objectAtIndex:x] addObject:n];
                }
            }
        }
    }
    

    but I'd like a cleaner, more succinct solution.

  • Nikita Zhuk
    Nikita Zhuk about 15 years
    Using NSArchiver and NSUnarchiver is a very heavy solution performance-wise, if your arrays are large. Writing a generic NSArray category method which uses NSCopying protocol will do the trick, causing a simple 'retain' of immutable objects and a real 'copy' of mutable ones.
  • Ed Marty
    Ed Marty about 15 years
    Seems to be the correct answer. The API states each element gets an [element copyWithZone:] message, which may be what you were seeing. If you are in fact seeing that sending [NSMutableArray copyWithZone:nil] doesn't deep copy, then an array of arrays may not copy correctly using this method.
  • quantumpotato
    quantumpotato about 13 years
    Hm, I got "*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Turn copyWithZone:]: unrecognized selector sent to instance 0x4e327a0'" (I have an array of turns).
  • Chris Hillery
    Chris Hillery almost 13 years
    @quantumpotato: You need to implement the NSCopying protocol on your Turn class. (Yes, I realize this is very late.)
  • Joe D'Andrea
    Joe D'Andrea over 12 years
    I don't think this will work as expected. From the Apple docs: "The copyWithZone: method performs a shallow copy. If you have a collection of arbitrary depth, passing YES for the flag parameter will perform an immutable copy of the first level below the surface. If you pass NO the mutability of the first level is unaffected. In either case, the mutability of all deeper levels is unaffected." The SO question concerns deep mutable copies.
  • Wienke
    Wienke almost 12 years
    It's good to be cautious about the expense, but would NSCoding really be more expensive than the NSCopying used in the initWithArray:copyItems: method? This archiving/unarchiving workaround seems very useful, considering how many control classes conform to NSCoding but not to NSCopying.
  • Brett
    Brett over 11 years
    I would highly recommend that you never use this approach. Serialization is never faster than just copying memory.
  • resting
    resting over 11 years
    why isn't initWithArray documented in NSMutableArray Class Reference?
  • Cameron Lowell Palmer
    Cameron Lowell Palmer about 11 years
    This is an incomplete answer. This results in a one-level deep copy. If there are more complex types within the Array it will not provide a deep copy.
  • user523234
    user523234 about 11 years
    If you have custom objects, make sure to implement encodeWithCoder and initWithCoder so to comply with NSCoding protocol.
  • Admin
    Admin almost 11 years
    This is correct. Regardless of popularity or prematurely-optimized edge-cases about memory, performance. As an aside, this ser-derser hack for deep copy is used in many other language environments. Unless there's obj dedupe, this guarantees a good deep copy completely separate from the original.
  • Admin
    Admin almost 11 years
  • Mark Amery
    Mark Amery over 10 years
    @resting Because it's an NSArray method, not unique to NSMutableArray.
  • devios1
    devios1 over 10 years
    This can be a deep copy, depending on how copyWithZone: is implemented on the receiving class.
  • VH-NZZ
    VH-NZZ about 9 years
    Obviously programmer's discretion is strongly advised when using serialization.
  • Nikolai Ruhe
    Nikolai Ruhe over 8 years
    You have to specify NSJSONReadingMutableContainers for the use case in this question.