Why NSUserDefaults return 'nil'?

百般思念 提交于 2019-12-25 04:24:26

问题


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.



来源:https://stackoverflow.com/questions/24695622/why-nsuserdefaults-return-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!