NSUserDefaults boolforKey 设计上的限制吗?
NSUserDefaults
API 文档具有 boolForKey:
消息,其描述如下 -
boolForKey:
返回与指定键关联的布尔值。
- (BOOL)boolForKey:(NSString *)defaultName
返回值 如果布尔值与用户默认值中的 defaultName 关联,则返回该值。否则,返回NO。
如果 [[NSUserDefaults standardUserDefaults] boolForKey:@"some_Key"]
返回一个 NO,则可能是因为该键不存在,或者该键存在并且具有一个 boolean
数值编号我们如何区分?事到如今,我只能从一开始就避免陷入这种境地。
The NSUserDefaults
API documentation has the boolForKey:
message which is described like this -
boolForKey:
Returns the Boolean value associated with the specified key.
- (BOOL)boolForKey:(NSString *)defaultName
Return Value
If a boolean value is associated with defaultName in the user defaults, that value is returned. Otherwise, NO is returned.
Given that a [[NSUserDefaults standardUserDefaults] boolForKey:@"some_Key"]
gives back a NO it can be either because the key does not exist or the key exists and has a boolean
value NO. How can we differentiate? As of now, I can only avoid getting into this situation in the first place.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您错误地使用了用户默认值。在启动应用程序时,您应该使用包含所有首选项的默认值的字典来调用
-[NSUserDefaults registerDefaults:]
。然后,如果用户未设置首选项,
-boolForKey
将返回默认值。You are using the user defaults incorrectly. At the launch of your app, you are supposed to call
-[NSUserDefaults registerDefaults:]
with a dictionary that contains the default values for all preferences.Then, if the user has not set a preference,
-boolForKey
will return the default value.也可以使用
-objectForKey:
方法。这将告诉您该密钥是否存在。Use the
-objectForKey:
method as well. This will tell you whether the key exists.