How NSCoding and NSKeyedArchiver/Unarchiver Work Together to Encode/Decode Objects

Mark van Wijnen
3 min readAug 15, 2022
Photo by Erda Estremera on Unsplash

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.

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 Book class.

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.

Archiving

--

--

Mark van Wijnen

macOS/iPadOS/iOS/watchOS/visionOS developer and SwiftUI enthousiast. “Stay Hungry, Stay Foolish!” — Steve Jobs