Graphics Programs Reference
In-Depth Information
NSKeyedArchiver and NSKeyedUnarchiver
You now have a place to save data on the filesystem and a model object that can be saved
to the filesystem. The final two questions we must answer are: how do we kick off the sav-
ing and loading processes and when do we do it? To save
BNRItem
s, you will use the
class
NSKeyedArchiver
when the application “exits.”
In
BNRItemStore.h
, declare a new method.
- (BOOL)saveChanges;
Implement this method in
BNRItemStore.m
to send the message
archiveRootOb-
ject:toFile:
to the
NSKeyedArchiver
class.
- (BOOL)saveChanges
{
// returns success or failure
NSString *path = [self itemArchivePath];
return [NSKeyedArchiver archiveRootObject:allItems
toFile:path];
}
The
archiveRootObject:toFile:
method takes care of saving every single
BNRItem
in
allItems
to the
itemArchivePath
. Yes, it is that simple. Here's how it
works.
The method begins by creating an instance of
NSKeyedArchiver
. Then, it sends the
message
encodeWithCoder:
to the root object (in our case,
allItems
).
NSKeyedArchiver
is a subclass of
NSCoder
, so we can pass this new instance of
NSKeyedArchiver
as the argument to
encodeWithCoder:
.
The
allItems
array then sends
encodeWithCoder:
to all of the objects it contains,
passing the same
NSKeyedArchiver
. The contents of this array - a bunch of
BNRItem
s - then encode their instance variables into the very same
NSKeyedArchiver
(
Figure 14.3
). Once all of these objects have been encoded, the
NSKeyedArchiver
writes the data it collected to the
path
.
Figure 14.3 Archiving an array