O'Reilly logo

Cocoa in a Nutshell by James Duncan Davidson, Michael Beam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Archiving Objects

Archiving an object (or a collection of interconnected objects, known as a graph) into a NSData representation is often useful or necessary. Objects that are archived into an NSData object can be transported over network connections or interprocess communication channels and saved to the filesystem. Later, the original graph of objects can be reconstituted from the archive data.

Foundation provides five classes to support the creation and extraction of archives, all subclasses of NSCoder:

  • NSArchiver

  • NSUnarchiver

  • NSKeyedArchiver

  • NSKeyedUnarchiver

  • NSPortCoder

NSCoder declares the common interface for encoding and decoding objects and other Objective-C data types. For example, the encodeObject method encodes an object into an archive, and methods such as encodeInt: and encodeRect: support encoding C data types such as integers and common Cocoa data structures.

NSCoder does not implement these methods; it is an abstract class. Rather, subclasses implement the appropriate methods for their particular purpose. NSArchiver and NSUnarchiver provide a straightforward way of encoding and decoding objects and scalars, but they have limitations. The biggest limitation is that objects in an archive can be decoded only in the same order in which they were encoded. Because of this constraint, changing an encoding system is difficult once it has been established publicly.

Keyed Archiving

The NSKeyedArchiver and NSKeyedUnarchiver classes solve this problem by associating ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required