xcode 如何测试 BOOL 是否存在于 NSUserDefaults 用户设置中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9971811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I test if BOOL exists in NSUserDefaults user settings?
提问by Justin Copeland
I set a BOOL value in NSUserDefaults as follows.
我在 NSUserDefaults 中设置了一个 BOOL 值,如下所示。
[userDefaults setBool:NO forKey:@"theKeyOfMyBOOL"];
Somewhere else in my code, I want to perform some action if the key "theKeyOfMyBOOL" is not set in NSUserDefaults. How do I verify whether this key was set? If I do
如果在 NSUserDefaults 中未设置键“theKeyOfMyBOOL”,我想在代码的其他地方执行一些操作。如何验证是否设置了此密钥?如果我做
[userDefaults boolForKey:@"theKeyOfMyBOOL"];
then the value returned could be nil, which evaluates to false I believe, or the actual BOOL value of NO, which values to false.
那么返回的值可能是 nil,我相信它的计算结果为 false,或者 NO 的实际 BOOL 值,其值为 false。
However, I need to differentiate between these two values (as well as YES of course). How do I reliably do that?
但是,我需要区分这两个值(当然还有 YES)。我如何可靠地做到这一点?
回答by jrturton
[userDefaults boolForKey:@"theKeyOfMyBOOL"];
returns a BOOL, so either YES
or NO
(not nil
).
[userDefaults boolForKey:@"theKeyOfMyBOOL"];
返回一个 BOOL,所以要么YES
or NO
(not nil
)。
Internally, it is stored as an NSNumber
. So, if you call
在内部,它存储为NSNumber
. 所以,如果你打电话
[userDefaults objectForKey:@"theKeyOfMyBOOL"];
you will be given an NSNumber
, if you have ever stored anything, or nil
, if you have not.
NSNumber
如果您曾经存储过任何东西,您将获得一个,或者nil
,如果您没有存储过。