Deep Copy and Shallow Copy

爱⌒轻易说出口 提交于 2019-12-17 17:38:44

问题


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 that when we made a shallow copy by

 newArray = [NSmutableArray arrayWithArray:oldArray];

the new array will point to oldArray. (As from the figure). Now what happen when I remove object from newArray? As from figure, it should remove same element from oldArray too !!! It seems like

newArray = oldArray is a shallow copy and newArray = [NSmutableArray arrayWithArray:oldArray]; is deep copy. Is it right?


回答1:


newArary = oldArray isn't a copy at all. You end up with two pointers pointing to the exact same memory location.

newArray = [NSMutableArray arrayWithArray:oldArray]; is a shallow copy. You end up with two distinct arrays, so if you were to remove or add items from one array, it wouldn't affect the other array. However, the items in the two arrays are identical. If the first element of oldArray were an NSMutableDictionary and you added a key to it, you'd see that change on the first element of newArray as well (since those two objects are the same).

To do a deep copy, you would have to make a new array, and each element of the new array would be a deep copy of the corresponding element of the old array. (Yes, that definition is recursive).




回答2:


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.




回答3:


You can also call [[NSArray alloc] initWithArray:arraytoBeCopied copyItems:YES];




回答4:


In Objective-C "Copy" keyword just increase the "Retain Count" of the object. So only use of "Copy" will not perform a copy.

But when we make a change in object, then Objective-C create a copy of the original object at that time.

Please correct me if i am wrong.

Thanks



来源:https://stackoverflow.com/questions/9912794/deep-copy-and-shallow-copy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!