Question

How do I check if there is already data stored in the NSUserdefaults? right now the code crashes when it is trying to load not existing data.

I tried:

NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSString *string = [ud objectForKey:@"scoreStringKey"];
if (string) 
{
    highScore = string.intValue;   
}
else
{        
    highScore = 0;
}
Was it helpful?

Solution

objectForKey will return nil if no key found Reference

intValue is a method not attribute. Link

NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSString *string = [ud objectForKey:@"scoreStringKey"];
if (string != nil) 
{
    highScore = [string intValue];   <--- right way to convert into integer
}    
else
{        
    highScore = 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top