Reputation: 29896
I have some code in my classes to read from NSUserDefaults
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
score = [defs integerForKey:@"score"];
this causes a crash.
Im guessing it is because the score value is nil or doesnt exist.
How can I check if it is nil?
EDIT.
The following code causes a crash when storing to NSUserDefaults.
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
[defs setInteger:0 forKey:@"score"];
[defs setInteger:3 forKey:@"lives"];
[defs release];
Im not sure what the issue is
On some crashes there isnt even a crash report in the console.
Thanks
Upvotes: 1
Views: 1928
Reputation: 31304
As per the documentation, "if the specified key does not exist, this method returns 0". So integerForKey will always return an NSInteger, even if you haven't set it.
Edit: Now you've edited your question, I can see the problem. You are releasing NSUserDefaults. There is no reason to do this. Remove the [release] line from your code.
[NSUserDefaults standardUserDefaults] returns a singleton class. You don't own it, so you shouldn't release it. Review the Apple Memory Mangement Rules if you're confused about when to retain/release.
Upvotes: 9