How NSCoding and NSKeyedArchiver/Unarchiver Work Together to Encode/Decode Objects
The NSCoding
protocol declares how an instance of a class can be encoded or decoded. This capability is then used byNSKeyedArchiver
(a NSCoder
) to encode the instance into an architecture-independent format suitable for archiving to disk or for distribution over the network. After that NSKeyedUnarchiver
is used to decode the data back to the original instance.
Implementing NSCoding
Implementing NSCoding
is really easy. We just need to add two methods to our class init?(coder: NSCoder)
and encode(with coder: NSCoder)
. The first method encodes an object. The second one decodes the data to instantiate a new object.
In short, encode(with:)
is the encoder and init(coder:)
is the decoder.
For a coding example let’s create a Book
class that holds different data types.
To conform to NSCoding
we add the protocol to the class declaration and add the two required methods to the class.