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, and NSString.

  • Add the state elements to the dictionary or the array.

  • Serialize the dictionary or the array into an NSData object using the NSPropertyList-Serialization 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 the Documents directory.

  • To restore the state, load the written file into an NSData object and use the NSPropertyListSerialization class method to obtain the dictionary or the array.

In the following, we give an example of saving/restoring ...

Get iPhone SDK Programming: Developing Mobile Applications 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.