简体   繁体   English

如何转换和比较NSNumber和BOOL?

[英]How to convert and compare NSNumber to BOOL?

First I convert BOOL value to NSNumber in order to put it into NSUserDefaults. 首先,我将BOOL值转换为NSNumber,以便将其置于NSUserDefaults中。 Later I would like to retrieve the BOOL value from the NSUserDefaults, but obviously I get NSNumber instead of BOOL. 后来我想从NSUserDefaults中检索BOOL值,但显然我得到NSNumber而不是BOOL。 My questions are? 我的问题是?

  1. how to convert back from NSNumber to BOOL? 如何从NSNumber转换回BOOL?
  2. How to compare NSNumber to BOOL value. 如何比较NSNumber与BOOL值。

Currently I have: 目前我有:

if (someNSNumberValue == [NSNumber numberWithBool:NO]) {
    do something
}

any better way to to the comparison? 有什么比较好的方法吗?

Thanks! 谢谢!

You currently compare two pointers. 您目前比较两个指针。 Use NSNumber s methods instead to actually compare the two: 使用NSNumber的方法来实际比较两者:

if([someNSNumberValue isEqualToNumber:[NSNumber numberWithBool:NO]]) {
    // ...
}

To get the bool value from a NSNumber use -(BOOL)boolValue : 要从NSNumber获取bool值,请使用-(BOOL)boolValue

BOOL b = [num boolValue];

With that the comparison would be easier to read for me this way: 通过这种方式,这种比较对我来说更容易阅读:

if([num boolValue] == NO) {
    // ...
}

NSUserDefaults有两种透明操作布尔值的方法:

- (BOOL)boolForKey:(NSString *)defaultName

- (void)setBool:(BOOL)value forKey:(NSString *)defaultName

The ONLY way I managed to finagle a NSNumber 's "booleanity" from its NSConcreteValue (doh!) was with the following... 我设法从NSConcreteValue (doh!)中获得NSNumber的“booleanity”的唯一方法是使用以下内容...

id x = [self valueForKey:@"aBoolMaybe"];
if ([x respondsToSelector:@selector(boolValue)] && 
    [x isKindOfClass:objc_getClass("__NSCFNumber")])
    [self doSomethingThatExpectsABool:[x boolValue]];

Every other trick... FAILED . 其他所有技巧...... 失败 Buyer beware, this isn't foolproof ( __NSCFNumber may well be platform/machine specific - it is solely Apple's implementation detail )... but as they say.. nothing else worked! 买家要小心,这不是万无一失的( __NSCFNumber可能是平台/机器特定的 - 它只是Apple的实施细节 )......但正如他们所说的那样...... 没有其他工作!

Swift 4: 斯威夫特4:

let newBoolValue = nsNumberValue.boolValue

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM