The copy method returns an object created by implementing the NSCopying copyWithZone protocols:
If you send an NSString message with a copy:
NSString* myString; NSString* newString = [myString copy];
The return value will be NSString (not mutable)
The mutableCopy method returns an object created by implementing the NSMutableCopying protocol mutableCopyWithZone:
By sending:
NSString* myString; NSMutableString* newString = [myString mutableCopy];
The return value of WILL can be changed.
In all cases, the object must implement a protocol, which means that it will create a new copy object and return it to you.
In the case of NSArray, there is an additional level of complexity regarding shallow and deep copying.
A shallow copy of NSArray will only copy references to objects in the original array and place them in a new array.
As a result:
NSArray* myArray; NSMutableArray* anotherArray = [myArray mutableCopy]; [[anotherArray objectAtIndex:0] doSomething];
Will also affect the object with index 0 in the original array.
A deep copy will actually copy the individual objects contained in the array. This is done by sending each individual object the message "copyWithZone:".
NSArray* myArray; NSMutableArray* anotherArray = [[NSMutableArray alloc] initWithArray:myArray copyItems:YES];
Edited to remove my incorrect assumption about copying a mutable object
Corey Floyd Jan 04 2018-10-21T00: 00-01
source share