Graphics Programs Reference
In-Depth Information
Archiving
Any iOS application is really doing one thing: providing an interface for a user to manipu-
late data. Every object in an application has a role in this process. Model objects, as you
know, are responsible for holding on to the data that the user manipulates. View objects
simply reflect that data, and controllers are responsible for what is going on while the ap-
plication is running. Therefore, when talking about saving and loading data, we are almost
always talking about saving and loading model objects.
In Homepwner , the model objects that a user manipulates are instances of BNRItem .
Homepwner would actually be a useful application if instances of BNRItem persisted
between runs of the application, and in this chapter, we will use archiving to save and load
BNRItem s.
Archiving is one of the most common ways of persisting model objects on iOS. Archiving
an object involves recording all of its instance variables and saving them to the filesystem.
Unarchiving an object loads the data from the filesystem and creates objects from that re-
cord.
Classes whose instances need to be archived and unarchived must conform to the NSCod-
ing protocol and implement its two required methods, encodeWithCoder: and
initWithCoder: .
@protocol NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
@end
Make BNRItem conform to NSCoding . Open Homepwner.xcodeproj and add this
protocol declaration in BNRItem.h .
@interface BNRItem : NSObject <NSCoding>
Now we need to implement the required methods. Let's start with encodeWithCoder: .
When a BNRItem is sent the message encodeWithCoder: , it will encode all of its in-
stance variables into the NSCoder object that is passed as an argument. You can think of
this NSCoder object as a container for data that is responsible for organizing that data and
writing it to the filesystem. It organizes the data in key-value pairs.
Search WWH ::




Custom Search