I have read the answer for difference between deep copy and shallow copy from the post, What is the difference between a deep copy and a shallow copy? . Now I got some doubt
First of all, NSArray
's don't have a deep copy function. However, you can make a deep copy function by doing the following:
@interface NSArray(deepCopy)
-(NSArray *) deepCopy;
@end
@implementation
-(NSArray *) deepCopy
{
NSMutableArray *ret = [NSMutableArray array];
for (id val in self)
{
if ([val conformsToProtocol:@protocol(NSCopying)])
{
[ret addObject:[val copy]];
}
else
{
[ret addObject:val];
}
}
return ret;
}
@end
Second of all, newArray = oldArray
does not copy the array. It simply makes newArray
point to the array that oldArray
points to.
Third, +arrayWithArray:
does a shallow copy of the array, meaning the individual objects are NOT copied.