为什么 NSUserDefaults 返回“nil"? [英] Why NSUserDefaults return 'nil'?

查看:50
本文介绍了为什么 NSUserDefaults 返回“nil"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释一下为什么 NSUserDefaults 为一个不是的对象返回nil"?我有一个游戏设置的视图,有一个文本字段,用户可以在其中写下他的名字.我将此名称保存在 NSUserDefaults 中,并将其作为占位符供其他用户进入此视图时使用.我这样设置对象:

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];

和占位符:

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"];

变量name"nil".我真的不知道为什么会发生这种情况,因为设置视图中的相同代码返回名称而不是nil".

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".

推荐答案

尝试使用

[defaults synchronize];

改为

[[NSUserDefaults standardUserDefaults] synchronize];

抱歉重复 - @Gio Bact 向我询问此事.

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

这篇关于为什么 NSUserDefaults 返回“nil"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆