Return to the Main Index
Return to the Alphabetic Index

Copyright (c) 1994 by NeXT Computer, Inc. All Rights Reserved.


Adopted By: Various OpenStep classes

Declared In: Foundation/NSObject.h

Protocol Description

A class whose instances provide functional copies of themselves should adopt the NSCopying protocol. The exact meaning of copy can vary from class to class, but a copy must be a functionally independent object, identical to the original at the time the copy was made. Where the concept immutable vs. mutable applies to an object, this protocol produces immutable copies; see the NSMutableCopying protocol for details on making mutable copies. Property list classes (NSString, NSData, NSArray, and NSDictionary) guarantee immutable returned values.

In most cases, to produce a copy that's independent of the original, a deep copy must be made. A deep copy is one in which every instance variable of the receiver is duplicated, instead of referencing the variable in the original object. If the receiver's instance variables themselves have instance variables, those too must be duplicated, and so on. A deep copy is thus a completely separate object from the original; changes to it don't affect the original, and changes to the original don't affect it. Further, for an immutable copy, no part at any level may be changed, making a copy a snapshot of the original object.

Making a complete deep copy isn't always needed. Some objects can reasonably share instance variables among themselvesa static string object that gets replaced but not modified, for example. In such cases your class can implement NSCopying more cheaply than it might otherwise need to.

The typical usage of NSCopying is to create passing by value value objects.

Contrary to most methods, the returned object is owned by the caller, who is responsible for releasing it.

Copying Objects

- (id)copyWithZone:(NSZone *)zone Returns a new instance that's a functional copy of the receiver. Memory for the new instance is allocated from zone. For collections, creates a deep (recursive) copy. The copy returned is immutable if the consideration immutable vs. mutable applies to the receiving object; otherwise the exact nature of the copy is determined by the class. The returned object is owned by the caller, who is responsible for releasing it.