Protocol

NSCopying

A protocol that objects adopt to provide functional copies of themselves.

Declaration

protocol NSCopying

Overview

The exact meaning of “copy” can vary from class to class, but a copy must be a functionally independent object with values identical to the original at the time the copy was made. A copy produced with NSCopying is implicitly retained by the sender, who is responsible for releasing it.

NSCopying declares one method, copy(with:), but copying is commonly invoked with the convenience method copy(). The copy() method is defined for all objects inheriting from NSObject and simply invokes copy(with:) with the default zone.

Your options for implementing this protocol are as follows:

  • Implement NSCopying using alloc and init... in classes that don’t inherit copy(with:).

  • Implement NSCopying by invoking the superclass’s copy(with:) when NSCopying behavior is inherited. If the superclass implementation might use the NSCopyObject function, make explicit assignments to pointer instance variables for retained objects.

  • Implement NSCopying by retaining the original instead of creating a new copy when the class and its contents are immutable.

If a subclass inherits NSCopying from its superclass and declares additional instance variables, the subclass has to override copy(with:) to properly handle its own instance variables, invoking the superclass’s implementation first.

Topics

Copying

func copy(with: NSZone?) -> Any

Returns a new instance that’s a copy of the receiver.

Required.

Relationships

Conforming Types

See Also

Copying

protocol NSMutableCopying

A protocol that mutable objects adopt to provide functional copies of themselves.

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software