How NSCoding and NSKeyedArchiver/Unarchiver Work Together to Encode/Decode Objects
NSCoding protocol declares how an instance of a class can be encoded or decoded. This capability is then used by
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.
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.
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.
Implementing NSKeyedArchiver / NSKeyedUnarchiver
We can now use
NSKeyedArchiver, a concrete subclass of
NSCoder, to encode instances of
Book into an architecture-independent format.
For the examples below we use an array named
books that hold instances of our
Write to UserDefaults
While it is not advisable to store an entire object graph into
UserDefaults, it can be useful to encode compound objects in this way, such as “current user” objects.