122

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.

4
  • 1
    maybe some of the confusion is because the behavior of -copy on immutable collections changed between Mac OS X 10.4 and 10.5: developer.apple.com/library/mac/releasenotes/Cocoa/… (scroll down to "Immutable collections and copy behavior") Commented Jan 14, 2011 at 22:37
  • 1
    @AndrewGrant On further thought, and with respect, I disagree that deep copy is a well-defined term. Depending upon what source you read, it's unclear whether unlimited recursion into nested data structures is a requirement of a 'deep copy' operation. In other words, you will get conflicting answers on whether a copy operation that creates a new object whose members are shallow copies of the members of the original object is a 'deep copy' operation or not. See stackoverflow.com/a/6183597/1709587 for some discussion of this (in a Java context, but it's relevant all the same). Commented Sep 1, 2013 at 21:57
  • @AndrewGrant I have to back up @MarkAmery and @Genericrich. A deep copy is well defined if the root class used in a collection and all its elements is copyable. This is not the case with NSArray (and other objc collections). If an element does not implement copy, what shall be put into the "deep copy"? If the element is another collection, copy does not actually yield a copy (of the same class). So I think it's perfectly valid to argue about the type of copy wanted in the specific case. Commented Oct 12, 2015 at 18:40
  • @NikolaiRuhe If an element does not implement NSCopying/-copy, then it is not copyable— so you should never try to make a copy of it, because that's not a capability it was designed to have. In terms of Cocoa's implementation, non-copyable objects often have some C backend state they're tied to, so hacking a direct-copy of the object could lead to race conditions or worse. So to answer “what shall be put into the ‘deep copy’” — A retained ref. The only thing you can put anywhere when you have a non-NSCopying object. Commented Feb 11, 2017 at 2:18

6 Answers 6

216

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.

Sign up to request clarification or add additional context in comments.

8 Comments

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.
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.
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.
@resting Because it's an NSArray method, not unique to NSMutableArray.
This can be a deep copy, depending on how copyWithZone: is implemented on the receiving class.
|
65

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))

5 Comments

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.
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.
I would highly recommend that you never use this approach. Serialization is never faster than just copying memory.
If you have custom objects, make sure to implement encodeWithCoder and initWithCoder so to comply with NSCoding protocol.
Obviously programmer's discretion is strongly advised when using serialization.
35

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]];

2 Comments

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.
8

For Dictonary

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

For Array

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

Comments

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.

Comments

2

I have a workaround if trying to achieve deep copy for JSON compatible data.

Simply take NSData of NSArray using NSJSONSerialization and then recreate JSON Object, this will create a complete new and fresh copy of NSArray/NSDictionary with new memory references of them.

But make sure the objects of NSArray/NSDictionary and their children must be JSON serializable.

NSData *aDataOfSource = [NSJSONSerialization dataWithJSONObject:oldCopy options:NSJSONWritingPrettyPrinted error:nil];
NSDictionary *aDictNewCopy = [NSJSONSerialization JSONObjectWithData:aDataOfSource options:NSJSONReadingMutableLeaves error:nil];

1 Comment

You have to specify NSJSONReadingMutableContainers for the use case in this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.