Storing data on disk and getting it back into memory is one of the basics tasks of almost all applications. Cocoa provides developers some simple and powerful ways of accomplishing these tasks, through the NSArchiver and NSUnarchiver classes. They will take care of cross-platform issues like byte order (Intel vs. Power PC) and data type size (32-bit vs. 64-bit processors).
You’ll probably use NSKeyedArchiver and NSKeyedUnarchiver subclasses to store and retrieve your app’s data. To do so you’ll have to implement NSCoding protocol on all of the application’s objects, which requires two methods, encodeWithCoder: and initWithCoder:. The NSCoding protocol is another example of the Template pattern, covered in Chapter 4.
To perform the archiving, you call NSKeyedArchiver’s class method +(NSData *)archivedDataWithRootObject:(id)rootObject like this:
Each object will archive its sub-objects (array elements, instance variables, etc.) via initWithCoder:, which in turn archive their sub-objects. If the archiver encounters an object a second time, it stores a token instead of archiving it again, in order to prevent an endless loop of objects archiving each other.
To extract the data, call NSKeyedUnArchiver’s method +(id)unarchiveObjectWithData:(NSData *)theData like this:
The examples in Hillegass’s book and the Apple documentation are easy to follow and will probably suffice to teach the technique to you. The good trick I got out of this chapter is to define a static NSString variable for keys: this way the compiler can catch mis-spellings. If you mis-spell a string, strange things may happen during execution that may be hard to figure out, but if you mis-spell a variable name the compiler will flag the error. Let GCC do the debugging for you! The code that demonstrates the technique is on page 129.
Some of the example code in this chapter uses comes from a program called WordPuzzle. The book claims that you can download WordPuzzle from the book’s website, but I can’t find it in the things I’ve downloaded. I left a comment on the book’s web site asking about that a couple of weeks ago, but haven’t heard back yet.