O'Reilly logo

Learning Cocoa by Apple Computer Inc

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

Flatten the Object Network: Coding and Archiving

Virtually all applications need a way to make some of their objects persistent. For example, the Expenses application that you created in the previous section doesn’t save the state of the data model, so you’ll lose all of your expenses information as soon as you quit. Cocoa applications typically use coding and archiving to store document contents and other critical application data to disk for later retrieval. Some applications may also use coding and archiving to send objects over a network to another application. (For instance, in case you want to send a set of expenses to a friend.)

In this section you will modify the simple expense-tracking application from the previous section to use coding and archiving so it can save and reload the array of expenses.

NSCoder and NSArchiver

Coding, as implemented by NSCoder, takes a connected group of objects such as those in an application (an object graph) and serializes that data, capturing the state, structure, relationships, and class memberships of the objects. A subclass of NSCoder, NSArchiver extends this behavior by storing the serialized data in a file.

When archiving an object graph’s root object, archive not only that object, but all other objects the root object references, all objects those second-level objects reference, etc. To be archived, though, objects must conform to the NSCoding protocol (consisting of the encodeWithCoder: and initWithCoder: methods).

Add ...

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