Why NSUserDefaults return 'nil'?

2019-09-05 22:06发布

问题:

can someone explain me why NSUserDefaults is returning me "nil" for an object that is not? I have a view with some settings for a game, there is a textfield in where user can write his name. I save this name in NSUserDefaults and put it as placeholder for the other times user enter this view. I set the object like that:

NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults]; 
NSString *fieldName = _nameField.text;
[defaults setObject:fieldName forKey:@"playerName"];
[[NSUserDefaults standardUserDefaults] synchronize];

And the placeholder:

NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
_nameField.placeholder = [defaults objectForKey:@"playerName"];

And this works perfectly! But, when a user end a game I want to save his score in a database, if this score is among the top ten; and of course I save the score with the name he wrote in the settings view. I found (putting some breakpoints) that after this code that runs when user made a record score:

NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString *name = [defaults objectForKey:@"playerName"];

The variabile name is "nil". I don't really know why this happens because the same code in the settings view returns the name and not a "nil".

回答1:

Try to use

[defaults synchronize];

istead

[[NSUserDefaults standardUserDefaults] synchronize];

Sorry for repeat - @Gio Bact asks me about it.