objective-c shallow- and deep-copy

本文介绍了对象复制的基本概念,探讨了对象复制的要求及实现方法,并对比了浅复制与深复制的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:https://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/ObjectCopying.html

Object Copying

Copying an object creates a new object with the same class and properties as the original object. You copy an object when you want your own version of the data that the object contains. If you receive an object from elsewhere in an application but do not copy it, you share the object with its owner (and perhaps others), who might change the encapsulated contents. If you are creating a subclass, you might consider making it possible for others to copy instances of your class. Generally, an object should be “copyable” when it is a value object—an object whose main purpose is to encapsulate some data.

Requirements for Object Copying

An object can be copied if its class adopts the NSCopying protocol and implements its single method, copyWithZone:. If a class has mutable and immutable variants, the mutable class should adopt the NSMutableCopying protocol (instead of NSCopying) and implement themutableCopyWithZone: method to ensure that copied objects remain mutable. You make a duplicate of an object by sending it a copy ormutableCopy message. These messages result in the invocation of the appropriate NSCopying or NSMutableCopying method.

Copies of objects can be shallow or deep. Both shallow- and deep-copy approaches directly duplicate scalar properties but differ on how they handle pointer references, particularly references to objects (for example, NSString *str). A deep copy duplicates the objects referenced while a shallow copy duplicates only the references to those objects. So if object A is shallow-copied to object B, object B refers to the same instance variable (or property) that object A refers to. Deep-copying objects is preferred to shallow-copying, especially with value objects.



Memory-Management Implications

Like object creation, object copying returns an object with a retain count of 1. In memory-managed code, the client copying the object is responsible for releasing the copied object. Copying an object is similar in purpose to retaining an object in that both express an ownership in the object. However, a copied object belongs exclusively to the new owner, who can mutate it freely, while a retained object is shared between the owners of the original object and clients who have retained the object.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值