Sunday, June 6, 2010

Saving persistent data on iphone while application exits

In many instances you would want to save application data when user exits your application. Since exiting an application programmatically is forbidden, the only way to exit any application in iphone is to press the home button. So how would you be able to save the data when user exits your application?

When the home button is pressed the UIApplication's delegate method applicationWillTerminate is called. So you can put the code to save your persistent data inside this method in your appDelegate class.

- (void)applicationWillTerminate:(UIApplication *)application{
//code to save your data
//If you don't know how data is saved, view this post on saving data in iphone
}


But there is still one problem. Since the above method will be in you appDelegate class, it might be troublesome to save data in other view controller classes. To solve this problem you can subscribe to notification named UIApplicationWillTerminateNotification.

-(void)viewDidLoad{
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appTermination:) name: @"UIApplicationWillTerminateNotification" object: nil];
}

-(void)appTermination:(id)sender{
//code to save your data
//If you don't know how data is saved, view this post on saving data in iphone
}


What this does is that it subscribes for the UIApplicationWillTerminateNotification notification in viewDidLoad method and sets appTermination method to be called when this notification is received

1 comment: