How to save variables after application shut down? How to save variables after application shut down? xcode xcode

How to save variables after application shut down?


You should store and load data from NSUserDefaults:

http://developer.apple.com/library/IOS/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];// to store[defaults setObject:[NSNumber numberWithInt:12345] forKey:@"myKey"];[defaults synchronize];// to loadNSNumber *aNumber = [defaults objectForKey:@"myKey"];NSInteger anInt = [aNumber intValue];


Check out the NSUserDefaults documentation. You can set arbitrary key-value pairs there which (as long as you call the shared user defaults object’s -synchronize at some point before your app terminates) will persist between launches.


You can save them in the NSUserDefaults. This is mainly used for preferences.

[[NSUserDefaults standardUserDefaults] setObject:someInteger forKey:@"someIntegerKey"];[[NSUserDefaults standardUserDefaults] synchronize];

You can also save them to a Property List file if you have more data you'd like to store.

NSDictionary *someDictionary = [NSDictionary dictionaryWithObjectsAndKeys:someInt1, @"someIntKey1", someInt2, @"someIntKey2", nil];[someDictionary writeToFile:somePath error:&error];

To save upon exiting the app place any code in

- (void)applicationWillTerminate:(UIApplication *)application