Saving and Reading Files
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 writeToFile... and initWithContentsOfFile... methods (as well as writeToURL... and 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access