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 presses 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
NSData
object using theNSPropertyListSerialization
class method.The
NSData
object represents the state information in either an XML or a binary format. For efficiency, use binary format.Write the
NSData
object into a local file in theDocuments
directory.To restore the state, load the written file into an
NSData
object and use theNSPropertyListSerialization
class method to obtain the dictionary or the array.
In the following, we give an example of ...
Get iPhone SDK 3 Programming: Advanced Mobile Development for Apple iPhone and iPod touch now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.