views:

285

answers:

3

Okay, I'm trying to write a high score function for my app.

My problem is that when no high score has been saved yet, my program crashes.

If I save it with:

[[NSUserDefaults standardUserDefaults] setObject:@"[given string]" forKey:@"firstName"];

first, it works fine. However, if I start up the program for the first time and try to view the high scores with the following code:

first = [[NSString alloc] initWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"firstName"]];

bad things happen.

Basically, is there away to see if nothing yet exist under firstName? Is there a way to initialize without erasing any name that might already be present?

Thanks.

+1  A: 

You could load "first" like this:

first = [[[NSUserDefaults standardUserDefaults] objectForKey:@"firstName"] retain];
if (!first) {
    // set default or do something else if there wasn't a value saved
    first = @"N/A";
}
gerry3
+2  A: 

The NSString documentation for initWithString: says

Parameters

aString

The string from which to copy characters. This value must not be nil.

The documentation for objectForKey: says

Return Value

The object associated with the specified key, or nil if the key was not found.

The problem seems to be that there is a nil returned when you try to retrieve firstName that doesn't exist yet and try to create a NSString with it as input.

leson
+1 Nice analysis.
gerry3
+2  A: 

The NSUserDefaults instance method registerDefaults: is meant for exactly this purpose: You can set default values for your preferences that will be overridden by any other value set for the same preference key. Just make sure to call it early enough that it will run before any code that needs to access your preferences.

Chuck