Search code examples
iphonexcodevariablessaveapplication-shutdown

How to save variables after application shut down?


I want to save some integers after application shut down and restore them after application opening, what is the easiest way to do this?


Solution

  • 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 load
    NSNumber *aNumber = [defaults objectForKey:@"myKey"];
    NSInteger anInt = [aNumber intValue];