Shallow Copies
There are a number of ways to make a shallow copy of a collection. When you create a shallow copy, the objects in the original collection are sent a retain
Listing 1
NSArray *shallowCopyArray=[someArray copyWithZone:nil]; |
|
NSDictionary *shallowCopyDict=[[NSDictionary alloc] initWithDictionary: someDictionary copyItems: NO]; |
These techniques are not restricted to the collections shown. For example, you can copy a set with the copyWithZone:
mutableCopyWithZone:
initWithArray:copyItems:
Deep Copies
There are two ways to make deep copies of a collection. You can use the collection’s equivalent of initWithArray:copyItems:
with YES
copyWithZone:
NSCopying
NSCopying
copyWithZone:
Listing 2
NSArray *deepCopyArray=[[NSArray alloc] initWithArray: someArray copyItems: YES]; |
This technique applies to the other collections as well. Use the collection’s equivalent of initWithArray:copyItems:
YES
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
Listing 3
NSArray* trueDeepCopyArray = [NSKeyedUnarchiver unarchiveObjectWithData: |
[NSKeyedArchiver archivedDataWithRootObje |
Copying and Mutability
When you copy a collection, the
-
copyWithZone:
makes the sufrace level immutable. All deeper levels have the mutability they previously had. -
initWithArray:copyItems:
with NO
as the second parameter gives the surface level the mutability of the class it is allocated as. All deeper levels have the mutability they previously had. -
initWithArray:copyItems:
with YES
as the second parameter gives the surface level the mutability of the class it is allocated as. The next level is immutable, and all deeper levels have the mutability they previously had. -
Archiving and unarchiving the collection leaves the mutability of all levels as it was before.