Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep Copy and Shallow Copy

Tags:

iphone

nsarray

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?

like image 606
rakeshNS Avatar asked Mar 28 '12 17:03

rakeshNS


People also ask

What is a deep copy?

A deep copy of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made.

What is shallow and deep copy in Python?

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

When would you use a shallow copy over a deep copy?

Shallow Copy stores the copy of the original object and points the references to the objects. Deep copy stores the copy of the original object and recursively copies the objects as well. Shallow copy is faster. Deep copy is comparatively slower.


1 Answers

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).

like image 113
yuji Avatar answered Oct 20 '22 23:10

yuji