To save or read a file, you are most likely to use one of the convenience methods for the class appropriate to the file’s contents. NSString, NSData, NSArray, and NSDictionary provide
initWithContentsOfFile... methods (as well as
initWithContentsOfURL...). Recall that NSArray and NSDictionary files are actually property lists (Chapter 10) and work only if all the contents of the array or dictionary are property list types (NSString, NSData, NSDate, NSNumber, NSArray, and NSDictionary).
If an object’s class adopts the NSCoding protocol, you can convert it to an NSData and back again using NSKeyedArchiver and NSKeyedUnarchiver. An NSData can be saved as a file or in a property list. Thus, NSCoding provides a way to save an object to disk. An example of doing this with a UIColor object appears in Chapter 10.
You can make your own class adopt the NSCoding protocol. This can become somewhat complicated because an object can refer (through an instance variable) to another object, which may also adopt the NSCoding protocol, and thus you can end up saving an entire graph of interconnected objects if you wish. However, I’ll confine myself to illustrating a simple case (and you can read the Archives and Serializations Programming Guide for more information).
Let’s say, then, that we have a simple Person class with a
firstName property and a
lastName property. We’ll declare that it adopts the NSCoding protocol:
@interface Person : NSObject ...