Let’s say that my application state is extracted into an object (so that all information specific to app instance is contained in one object) and that object supports nscoding protocol. How can i easily persist it and load it on exit/launch of my application?
My current code looks like this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
State* state = (State*)[defaults objectForKey:@"State"];
if(state!=nil)
{
viewController.state = state;
}
}
- (void)applicationWillTerminate:(UIApplication *)application {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.viewController.state forKey:@"State"];
}
But upon loading state is always nil… so I assume it is not the best pattern out there 🙂
It turns out that NSUserDefaults supports only Property List objects such as NSArray, NSData, etc… no custom objects unless you wrap it in nsdata
There are a number of ways of storing the state of your application before it exits and restoring it when it launches again. The best approach really depends on your application.
If you have a simple object model with a single root object and you tend to need the entire object model in memory at once, then you may find the NSCoding protocol (see link below) a good way of saving state.
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Protocols/NSCoding_Protocol/Reference/Reference.html
Any of the objects you want to persist should implement this protocol’s two methods:
Once you’ve implemented these methods in any of the objects you want to persist, you can serialise your object graph with something like this:
When you want to restore the archived objects:
Alternatively, if your application’s object model is slightly more complex you might consider using Core Data.
http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html
Finally, whilst the user defaults system can be used for storing and retrieving values, it is best used for simple application settings (or preferences). It isn’t really intended for saving your entire application’s state.