Tuesday, July 14, 2009

Saving State

So, how is it that when you restart a well-designed iPhone/iPodTouch application it restores to the state it was in when you left the application?

Enter the NSUserDefaults ... a Singleton in the Apple

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

[defaults setInteger:polygonShape.numberOfSides forKey:@"numberOfSides"];


The previous section stores a number off into the NSUserDefaults area at some point. Where this is called is up to you, the developer.

Then when you restart your application you simply see if this key exists, if it does you use it if not then use some appropriate defaults.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

int numberOfSides = [defaults integerForKey:@"numberOfSides"];

if(numberOfSides!=0) {

polygonShape.numberOfSides=numberOfSides;

numberOfSidesLabel.text = [NSString stringWithFormat:@"%d",numberOfSides];

}




No comments:

Post a Comment