Graphics Programs Reference
In-Depth Information
To be encoded, these objects must also conform to NSCoding . Check out the documenta-
tion for NSString and NSDate : they are NSCoding compliant.
The purpose of the key used when encoding is to retrieve the encoded value when this
BNRItem is loaded from the filesystem later. Objects being loaded from an archive are
sent the message initWithCoder: . This method should grab all of the objects that
were encoded in encodeWithCoder: and assign them to the appropriate instance vari-
able. Implement this method in BNRItem.m .
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
[self setItemName:[aDecoder decodeObjectForKey:@"itemName"]];
[self setSerialNumber:[aDecoder decodeObjectForKey:@"serialNumber"]];
[self setImageKey:[aDecoder decodeObjectForKey:@"imageKey"]];
[self setValueInDollars:[aDecoder decodeIntForKey:@"valueInDollars"]];
dateCreated = [aDecoder decodeObjectForKey:@"dateCreated"];
}
return self;
}
Notice that this method has an NSCoder argument, too. In initWithCoder: , the
NSCoder is full of data to be consumed by the BNRItem being initialized. Also notice
that you sent decodeObjectForKey: to the container to get objects back and de-
codeIntForKey: to get the valueInDollars .
In Chapter 2 , we talked about the initializer chain and designated initializers. The
initWithCoder: method isn't part of this design pattern; you will keep BNRItem 's
designated initializer the same, and initWithCoder: will not call it.
(By the way, archiving is how XIB files are created. UIView conforms to NSCoding .
Instances of UIView are created when you drag them onto the canvas area. When the
XIB file is saved, these views are archived into the XIB file. When your application
launches, it unarchives the views from the XIB file. There are some minor differences
between a XIB file and a standard archive, but overall, it's the same process.)
BNRItem s are now NSCoding compliant and can be saved to and loaded from the
filesystem using archiving. You can build the application to make sure there are no syntax
errors, but, we still need a way to kick off the saving and loading. We also need a place on
the filesystem to store the saved BNRItem s.
Search WWH ::




Custom Search