Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
The NSCoding protocol defines two methods that must be implemented on your object in order to be NSCoding compliant. The first is the -encodeWithCoder: method. This method is called by the archiver when it needs to serialize your object. It takes an NSCoder as a parameter. \NSCoder is an abstract base class. Typically the actual objects that will be passed to you will be instances of NSArchiver or NSKeyedArchiver. Using the NSCoder, you then archive the member variables of your object into it.
To serialize your member variables into the NSCoder, you use the methods on the instance of NSCoder which has been passed into your -encodeWithCoder: method. NSCoder provides a variety of methods for the purposes of encoding basic types as well as objects. To encode an object into an NSCoder, you use the NSCoder methods -encodeObject: or -encodeObject:forKey:. Not all NSCoder instances work the same. Some support keyed archiving and some do not. To determine if your instance of NSCoder supports keyed archiving, use the method -allowsKeyedCoding. This method returns YES if the instance of NSCoder supports keyed archiving. Any object which supports the NSCoding protocol can be encoded using the -encodeObject... methods. Most low level Foundation classes such as NSString, NSArray, and NSDictionary all do. An example implementation of an -encodeWithCoder: method encoding objects is shown in Listing 18.1.