深拷贝和浅拷贝 [英] Deep Copy and Shallow Copy

查看:119
本文介绍了深拷贝和浅拷贝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了帖子中深拷贝和浅拷贝之间差异的答案,深拷贝和浅拷贝有什么区别?。现在我有点怀疑,当我们通过

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];

新数组将指向oldArray。 (如图所示)。现在当我从newArray中删除对象时会发生什么?如图所示,它应该从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 是一个浅表副本, newArray = [NSmutableArray arrayWithArray :oldArray]; 是深拷贝。是不是?

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

推荐答案

newArary = oldArray 不是副本一点都不你最终得到两个指向完全相同内存位置的指针。

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]; 是一个浅层副本。最终得到两个不同的数组,因此如果要从一个数组中删除或添加项,则不会影响另一个数组。但是,两个数组中的是相同的。如果 oldArray 的第一个元素是 NSMutableDictionary ,并且您为其添加了一个键,则会看到该更改 newArray 的第一个元素(因为这两个对象是相同的)。

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

这篇关于深拷贝和浅拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆