[英]Why NSUserDefaults return 'nil'?
can someone explain me why NSUserDefaults is returning me "nil" for an object that is not? 有人可以向我解释为什么NSUserDefaults为不是的对象返回“ nil”吗? 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.
我将此名称保存在NSUserDefaults中,并将其用作占位符,以供用户在其他时间进入此视图。 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"
. 可变
name
为"nil"
。 I don't really know why this happens because the same code in the settings view returns the name and not a "nil". 我真的不知道为什么会这样,因为设置视图中的相同代码返回名称而不是“ nil”。
Try to use 尝试使用
[defaults synchronize];
istead 相反
[[NSUserDefaults standardUserDefaults] synchronize];
Sorry for repeat - @Gio Bact asks me about it. 很抱歉重复-@Gio Bact向我询问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.