A protocol that enables an object to be encoded and decoded for archiving and distribution.


protocol NSCoding


The NSCoding protocol declares the two methods that a class must implement so that instances of that class can be encoded and decoded. This capability provides the basis for archiving (where objects and other structures are stored on disk) and distribution (where objects are copied to different address spaces).

In keeping with object-oriented design principles, an object being encoded or decoded is responsible for encoding and decoding its instance variables. A coder instructs the object to do so by invoking encode(with:) or init(coder:). encode(with:) instructs the object to encode its instance variables to the coder provided; an object can receive this method any number of times. init(coder:) instructs the object to initialize itself from data in the coder provided; as such, it replaces any other initialization method and is sent only once per object. Any object class that should be codeable must adopt the NSCoding protocol and implement its methods.

It is important to consider the possible types of archiving that a coder supports. In macOS 10.2 and later, keyed archiving is preferred. You may, however, need to support classic archiving. For details, see Archives and Serializations Programming Guide.


Initializing with a coder

init?(coder: NSCoder)

Returns an object initialized from data in a given unarchiver.


Encoding with a coder

func encode(with: NSCoder)

Encodes the receiver using a given archiver.



Conforming Types

See Also

First Steps

Encoding and Decoding Custom Types

Make your data types encodable and decodable for compatibility with external representations such as JSON.

typealias Codable

A type that can convert itself into and out of an external representation.

protocol NSSecureCoding

A protocol that enables encoding and decoding in a manner that is robust against object substitution attacks.