iPhone SDK Programming: Developing Mobile Applications for Apple iPhone and iPod touch
by Maher Ali
Appendix A. Saving and Restoring App State
Since at most one application can run at a given time, your application should give the user the illusion of being active all the time even if the user hit the Home button. To achieve that, your application should save its current state (e.g., which level of hierarchy it is currently displaying, the current search term, etc.) when the application is terminated, and restore that state when it is relaunched.
There are several ways in which you can maintain this state information. You can, for example, use the SQLite database or flat-files. A property list, however, is ideal for this situation and is the subject of this appendix.
To use property lists for capturing/restoring the state of an application, you need to follow the following guidelines:
Represent the state in a dictionary or in an array.
The state elements can be instances of
NSDictionary, NSArray, NSData, NSDate, NSNumber, andNSString.Add the state elements to the dictionary or the array.
Serialize the dictionary or the array into an
NSDataobject using theNSPropertyList-Serializationclass method.The
NSDataobject represents the state information in either an XML or a binary format. For efficiency, use binary format.Write the
NSDataobject into a local file in theDocumentsdirectory.To restore the state, load the written file into an
NSDataobject and use theNSPropertyListSerializationclass method to obtain the dictionary or the array.
In the following, we give an example of saving/restoring ...