I have an NSMutableArray of custom objects (based on NSObject) which I want to copy into a new array. But I want it to be a deep copy.
How do I go about doing this? Do I need to implement the NSCopying protocol in my custom object?
Thanks
I have an NSMutableArray of custom objects (based on NSObject) which I want to copy into a new array. But I want it to be a deep copy.
How do I go about doing this? Do I need to implement the NSCopying protocol in my custom object?
Thanks
Yes, you need to indicate that your custom class adheres to the NSCopying
protocol and then you implement the copyWithZone:
method. This allows your class to be copied. In your implementation of copyWithZone:
you need to decide how much of the internals also need deep copying.
Now if you do a deep copy of the array, the new array will include copied versions of your object and not just references to the originals.
Please note that a regular copy of an array doesn't do a deep copy. To make a deep copy you want something like:
NSArray *deepCopyArray=[[NSArray alloc] initWithArray:someArray copyItems:YES];
Deep copying an array can be done by going through all elements manually. This is necessary if the objects require further deep copying.
NSMutableArray *deepCopied = [NSMutableArray arrayWithCapacity:[array count]];
// assumes your objects know how to "deepCopy"
for (id object in array)
{
// if not ARC or GC:
[deepCopied addObject:[[object deepCopy] aurorelease]];
// if ARC or GC
[deepCopied addObject:[object deepCopy]];
}
Otherwise:
NSArray *deepCopied = [[NSArray alloc] initWithArray:array copyItems:YES];
There is a category method described in an answer here that may help if you need to make a lot of deep copies.