djskinner
djskinner

Reputation: 8125

iOS NSUserDefaults check if float key exists

I want to check if a float stored in NSUserDefaults is pre-existing. The Apple documentation suggests that it floatForKey will return 0 if the key does not exist.

How do I correctly tell the difference between a stored 0 and a non-existent key?

Upvotes: 2

Views: 2874

Answers (3)

djskinner
djskinner

Reputation: 8125

Thanks to woz and Bernd Rabe. My solution is this:

    //Set volume
    id savedVolume = [[NSUserDefaults standardUserDefaults] objectForKey:@"GameVolume"];
    if (savedVolume == nil) //Check if volume not already saved (e.g. new install)
    {
        //Set default volume to 1.0
        float defaultVolume = 1.0;
        [[ApplicationController controller].soundManager setGlobalVolume: defaultVolume];
        [[NSUserDefaults standardUserDefaults] setFloat:defaultVolume forKey:@"GameVolume"];
    } else {
        float savedVolume = [[NSUserDefaults standardUserDefaults] floatForKey:@"GameVolume"];
        [[ApplicationController controller].soundManager setGlobalVolume: savedVolume];
    }

Does that look safe enough?

Upvotes: 0

woz
woz

Reputation: 10994

A reliable way to see if a default has been set is:

if (![[NSUserDefaults standardUserDefaults] valueForKey:@"foo"]) { ... }

This works regardless of the data type.

Upvotes: 12

Bernd Rabe
Bernd Rabe

Reputation: 790

If the objectForKey is nil, no object exists, so there is no item stored in NSUserDefaults.

Upvotes: 0

Related Questions