Search code examples
cocoa-touchcore-dataxcode4int

Xcode: Saving an Int value


I have a simple counter application, i.e. the user presses a button to increase it by a value of their choice. I started the application production on a single view application. I now have the need to make it so that when the app is closed it saves the last value of the counter. Then when the app reopens it needs to load the value of the counter back into place. The value needs to be saved and reloaded simply by closing and opening the app i.e. no buttons are needed to be pressed.

My counter variable is an Int value called counter. The view controllers are simply named viewController.h/m.

I have no idea how to set all of this up, I assume I need coreData to do this. How do I set up coreData? Do I code in my delegate of viewController? If this is not the best way to do it please provide a way to do it in a more effective way!

Thanks very much for any help, simple instructions appreciated most of all. I have had a look at other example of this but none seemed to provide what I need or were simple enough to understand. Please provide an answer on this thread!

Hugh


Solution

  • It's easiest to simply use NSUserDefaults instead of Core Data.

    To save:

    [[NSUserDefaults standardUserDefaults] setInteger:counter forKey:@"counter"]
    

    To read:

    NSInteger counter = [[NSUserDefaults standardUserDefaults] integerForKey:@"counter"];
    

    Take a look at UIApplicationDelegate to find what methods you should place the code in. It will likely be in your AppDelegate in one of the following methods:

    Where to load the value:

    • -application:didFinishLaunchingWithOptions:
    • –applicationWillEnterForeground:

    Where to save the value:

    • -applicationDidEnterBackground:
    • –applicationWillTerminate:

    Exactly where depends on if you need to load and save the value when the user switches to another app, which is almost certainly the case as the app might be terminated when it is in a frozen state due to memory pressure. In this case you would want to make sure the value was saved when the app was backgrounded (the user switched to a different app) and the value was restored when the app became the foreground app (the user switched back to your app).