简体   繁体   中英

How to convert and compare NSNumber to BOOL?

First I convert BOOL value to NSNumber in order to put it into NSUserDefaults. Later I would like to retrieve the BOOL value from the NSUserDefaults, but obviously I get NSNumber instead of BOOL. My questions are?

  1. how to convert back from NSNumber to BOOL?
  2. How to compare NSNumber to BOOL value.

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:

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

To get the bool value from a NSNumber use -(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...

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!

Swift 4:

let newBoolValue = nsNumberValue.boolValue

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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