2/15/2009

Save Your App's State (and Settings)

The iPhone (and I suppose Cocoa as well) makes it very easy to save and retrieve data. Most commonly, this will be settings of some sort, but you could save the state of your app so that when someone starts it again, it picks up from the same place, or something similar.

What you want to use is NSUserDefaults. Using it is extremely simple. First, just declare your NSUserDefaults pointer.

NSUserDefaults *myDefaultOptions = [NSUserDefaults standardUserDefaults];

To save an object (or variable), do something like the following:

[myDefaultOptions setObject:myTestString forKey:@"firstPlayerName"];

In this case, "firstPlayerName" is the name of the key that I'm saving the object to. It can match your in-use variable name if you want (which I often do). You might want to make a save method that gets called with a button press and writes out a bunch of objects at one. When you want to then to load the object again:

myTestString = [myDefaultOptions stringForKey:@"firstPlayerName"];

Basically, that's it, but you'll need to run a test on your loads so that when someone runs the program for the first time (or hasn't saved), then you'll take care of it. In the case of a string, if there isn't a corresponding NSUserDefaults entry for what you try to load, it comes up as NULL. So, after loading the save, you could run a quick check like the following:

if ([myTestString == NULL]) myTestString = @"Blah blah blah";

PRO-TIP: You can save arrays to NSUserDefaults and retrieve them easily, but there's a catch - even if you save out an NSMutableArray (one that's editable - NSArray is not), it will come back as immutable (uneditable). I ran into some crazy issues because of this, and it wound up being a pain to track down until I figured it out. It's actually an easy fix though - just add "mutableCopy" to the end of your read. So, it would look something like:

myArray = [[defaultOptions objectForKey:@"mySavedArray"] mutableCopy];

2 comments:

  1. Thanks So Much!!!
    I cant get mutable copy to work. Where would i add it here?

    - (void)applicationDidFinishLaunchingUIApplication *)application {
    projectsArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"projectsArray"];
    if (projectsArray == NULL) {
    projectsArray = [[NSMutableArray arrayWithObjects:@"New Project", nil] retain];
    }
    }

    - (void)applicationWillTerminateUIApplication *)application {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObjectrojectsArray forKey:@"projectsArray"];
    // Save data if appropriate
    }

    Any help would be sweet thanks!!!

    ReplyDelete
  2. You mean nil not NULL, right? Assuming myTestString is an object (NSString*)?

    ReplyDelete