如何测试NSUserDefaults用户设置中是否存在BOOL?

时间:2022-10-17 07:35:36

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)。我如何可靠地做到这一点?

1 个解决方案

#1


43  

[userDefaults boolForKey:@"theKeyOfMyBOOL"]; returns a BOOL, so either YES or NO (not nil).

[userDefaults boolForKey:@“theKeyOfMyBOOL”];返回BOOL,所以YES或NO(不是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。

#1


43  

[userDefaults boolForKey:@"theKeyOfMyBOOL"]; returns a BOOL, so either YES or NO (not nil).

[userDefaults boolForKey:@“theKeyOfMyBOOL”];返回BOOL,所以YES或NO(不是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。