NSUserDefaults. setValue起作用,而不是setBool [英] NSUserDefaults. setValue works, Not setBool
问题描述
我试图在NSUserDefaults中存储一些设置,但是似乎该应用程序不会存储setBool值.
I trying to store some settings in NSUserDefaults, but It seems that the app won't store the setBool values.
这有效:
[[NSUserDefaults standardUserDefaults] setValue: @"hello" forKey: @"test"];
[[NSUserDefaults standardUserDefaults] synchronize];
[[NSUserDefaults standardUserDefaults] setValue: @"hello" forKey: @"test"];
[[NSUserDefaults standardUserDefaults] synchronize];
当我终止应用程序并重新启动它时,该值已保存.但是,当我这样做时:
When I terminate the app and restart it, the value have been saved. However, when I do this:
[[NSUserDefaults standardUserDefaults] setBool: YES forKey: @"test"];
[[NSUserDefaults standardUserDefaults] synchronize];
关闭应用程序并重新启动后,它将无法保存.
[[NSUserDefaults standardUserDefaults] setBool: YES forKey: @"test"];
[[NSUserDefaults standardUserDefaults] synchronize];
It won't save after I close the app and restart it.
我应该提交错误报告,还是这里缺少什么?
Should I file a bug report, or is there something I'm missing here?
谢谢
我弄清楚我做错了什么.在AppDelegate中,我想检查是否设置了boolForKey,不是我这样做了:
I figure what I did wrong. In AppDelegate, I wanted to check if the boolForKey was set, and it it wasn't I did this:
if (![defaults boolForKey: @"test123"])
[defaults setBool: YES forKey: @"test123"];
...但是,当涉及到boolWithKey时,!"只需检查布尔值是否为是或否,而不是零即可.
... however, when it comes to boolWithKey, the "!" just check if the bool is YES or NO, not if its nil.
推荐答案
如何确定它不起作用?我尝试了您的代码,它对我有用.确定要在编写布尔值之后以正确的方式读取布尔值?
How can you be sure its not working? I tried your code and it works for me. Are you sure you are reading the Boolean in the correct way AFTER you write it?
此代码应正常工作:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:NO forKey:@"test"];
[defaults synchronize];
BOOL myBool = [defaults boolForKey:@"test"];
这篇关于NSUserDefaults. setValue起作用,而不是setBool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!