65

What is the difference between copy and mutableCopy when used on either an NSArray or an NSMutableArray?

This is my understanding; is it correct?

// ** NSArray **
NSArray *myArray_imu = [NSArray  arrayWithObjects:@"abc", @"def", nil];

// No copy, increments retain count, result is immutable
NSArray *myArray_imuCopy = [myArray_imu copy];

// Copys object, result is mutable 
NSArray *myArray_imuMuta = [myArray_imu mutableCopy];

// Both must be released later

// ** NSMutableArray **
NSMutableArray *myArray_mut = [NSMutableArray arrayWithObjects:@"A", @"B", nil];

// Copys object, result is immutable
NSMutableArray *myArray_mutCopy = [myArray_mut copy];

// Copys object, result is mutable
NSMutableArray *myArray_mutMuta = [myArray_mut mutableCopy];

// Both must be released later
jscs
  • 62,161
  • 12
  • 145
  • 186
fuzzygoat
  • 25,797
  • 45
  • 159
  • 288
  • 1
    You have a mistake in your edit; not sure whether it's a typo or a misunderstanding. In the first code block, the variable myArray_imuMuta that's assigned to from mutableCopy is *mutable*, not immutable as your comment indicates. – Asher Dunn Jan 06 '10 at 19:29
  • Thank you, it was a mistake, I was getting confused with Xcode saying "Warning NSArray may not respond to add -addObject / -removeObjectAtIndex. I will change myArray_imuMuta to NSMutableArray. – fuzzygoat Jan 06 '10 at 22:01
  • @JamesHarnett - please stop the edits in the name of "ARC compatibility" - see [this meta post](http://meta.stackoverflow.com/questions/268309/is-it-okay-to-convert-non-arc-objective-c-answers-to-arc) for why. – Krease Dec 06 '14 at 07:12

8 Answers8

73

copy and mutableCopy are defined in different protocols (NSCopying and NSMutableCopying, respectively), and NSArray conforms to both. mutableCopy is defined for NSArray (not just NSMutableArray) and allows you to make a mutable copy of an originally immutable array:

// create an immutable array
NSArray *arr = [NSArray arrayWithObjects: @"one", @"two", @"three", nil ];

// create a mutable copy, and mutate it
NSMutableArray *mut = [arr mutableCopy];
[mut removeObject: @"one"];

Summary:

  • you can depend on the result of mutableCopy to be mutable, regardless of the original type. In the case of arrays, the result should be an NSMutableArray.
  • you cannot depend on the result of copy to be mutable! copying an NSMutableArray may return an NSMutableArray, since that's the original class, but copying any arbitrary NSArray instance would not.

Edit: re-read your original code in light of Mark Bessey's answer. When you create a copy of your array, of course you can still modify the original regardless of what you do with the copy. copy vs mutableCopy affects whether the new array is mutable.

Edit 2: Fixed my (false) assumption that NSMutableArray -copy would return an NSMutableArray.

Asher Dunn
  • 2,346
  • 16
  • 12
  • 4
    Sending -copy to an NSMutableArray does not normally return another mutable array. It certainly *could do so*, but in the usual case, it returns an immutable, constant-time access, array. – Mark Bessey Jan 04 '10 at 21:17
  • Oops, you are right. I misread the OP's code and thought he was modifying the result of -copy. It would make just as much sense for NSMutableArray's -copy to return another mutable array, so I (incorrectly) assumed that was the case. – Asher Dunn Jan 04 '10 at 21:19
  • Am I missing something as I can't find any reference to [mut remove: @"one"]; should this not be [mut removeObjectIdenticalTo: @"one"]; I just want to clarify for those reading this and trying to learn? – fuzzygoat Jan 05 '10 at 17:10
  • Oops, that should have been [mut removeObject: @"one"];. removeObject uses -isEqual to determine matches, and two strings are considered equal if they have the same content. removeObjectIdenticalTo only removes *the exact object* passed (it compares object addresses, not contents). [mut removeObjectIdenticalTo: @"one"] creates a new temporary NSString object, which is not in the array, and therefore cannot be removed from the array. – Asher Dunn Jan 06 '10 at 19:26
  • 5
    "copying an NSMutableArray may return an NSMutableArray" No, it NEVER returns an NSMutableArray. See http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmImplementCopy.html#//apple_ref/doc/uid/20000049-999791 "Where the concept “immutable vs. mutable” applies to an object, NSCopying produces immutable copies whether the original is immutable or not." – user102008 Jan 20 '11 at 23:42
  • nicely explained and a very impressive answer. Upvote for you... Good job – Abdul Yasin Oct 01 '18 at 10:15
8

I think you must have misinterpreted how copy and mutableCopy work. In your first example, myArray_COPY is an immutable copy of myArray. Having made the copy, you can manipulate the contents of the original myArray, and not affect the contents of myArray_COPY.

In the second example, you create a mutable copy of myArray, which means that you can modify either copy of the array, without affecting the other.

If I change the first example to try to insert/remove objects from myArray_COPY, it fails, just as you'd expect.


Perhaps thinking about a typical use-case would help. It's often the case that you might write a method that takes an NSArray * parameter, and basically stores it for later use. You could do this this way:

- (void) doStuffLaterWith: (NSArray *) objects {
  myObjects=[objects retain];
}

...but then you have the problem that the method can be called with an NSMutableArray as the argument. The code that created the array may manipulate it between when the doStuffLaterWith: method is called, and when you later need to use the value. In a multi-threaded app, the contents of the array could even be changed while you're iterating over it, which can cause some interesting bugs.

If you instead do this:

- (void) doStuffLaterWith: (NSArray *) objects {
  myObjects=[objects copy];
}

..then the copy creates a snapshot of the contents of the array at the time the method is called.

Mark Bessey
  • 19,065
  • 4
  • 44
  • 66
5

The "copy" method returns the object created by implementing NSCopying protocols copyWithZone:

If you send NSString a copy message:

NSString* myString;

NSString* newString = [myString copy];

The return value will be an NSString (not mutable)


The mutableCopy method returns the object created by implementing NSMutableCopying protocol's mutableCopyWithZone:

By sending:

NSString* myString;

NSMutableString* newString = [myString mutableCopy];

The return value WILL be mutable.


In all cases, the object must implement the protocol, signifying it will create the new copy object and return it to you.


In the case of NSArray there is an extra level of complexity regarding shallow and deep copying.

A shallow copy of an NSArray will only copy the references to the objects of the original array and place them into the new array.

The result being that:

NSArray* myArray;

NSMutableArray* anotherArray = [myArray mutableCopy];

[[anotherArray objectAtIndex:0] doSomething];

Will also affect the object at index 0 in the original array.


A deep copy will actually copy the individual objects contained in the array. This done by sending each individual object the "copyWithZone:" message.

NSArray* myArray;

NSMutableArray* anotherArray = [[NSMutableArray alloc] initWithArray:myArray
                                                       copyItems:YES];

Edited to remove my wrong assumption about mutable object copying

Corey Floyd
  • 25,769
  • 30
  • 123
  • 152
5
NSMutableArray* anotherArray = [[NSMutableArray alloc] initWithArray:oldArray
                                                           copyItems:YES];

will create anotherArray which is a copy of oldArray to 2 levels deep. If an object of oldArray is an Array. Which is generally the case in most applications.

Well if we need a True Deep Copy we could use,

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

This would ensure that all levels are actually copied retaining the mutability of the original object at each level.

Robert Clarence D'Almeida, Bangalore, India.

3

You're calling addObject and removeObjectAtIndex on the original array, rather than the new copy of it you've made. Calling copy vs mutableCopy only effects the mutability of the new copy of the object, not the original object.

Dewayne Christensen
  • 2,044
  • 13
  • 11
2

To state it simply,

  • copy returns an immutable (can't be modified) copy of the array,
  • mutableCopy returns a mutable (can be modified) copy of the array.

Copy (in both cases) means that you get a new array "populated" with object references to the original array (i.e. the same (original) objects are referenced in the copies.

If you add new objects to the mutableCopy, then they are unique to the mutableCopy. If you remove objects from the mutableCopy, they are removed from the original array.

Think of the copy in both cases, as a snapshot in time of the original array at the time the copy was created.

kgdesouz
  • 1,940
  • 3
  • 16
  • 21
Wizkid
  • 985
  • 9
  • 9
0
-(id)copy always returns a immutable one & -(id)mutableCopy always returns a mutable object,that's it.

You have to know the return type of these copying stuff and while declaring the new object which one will be assigned the return value must be of immutable or mutable one, otherwise compiler will show you error.

The object which has been copied can not be modified using the new one,they are totally two different objects now.

Sauvik Dolui
  • 5,060
  • 3
  • 29
  • 38
0

Assume

NSArray *A = xxx; // A with three NSDictionary objects
NSMutableArray *B = [A mutableCopy]; 

B's content is NSDictionary object not NSMutableDictionary, is it right?

ZYiOS
  • 5,084
  • 3
  • 36
  • 43