How to convert and compare NSNumber to BOOL?

后端 未结 4 1356
太阳男子
太阳男子 2020-12-28 12:45

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 NSN

相关标签:
4条回答
  • 2020-12-28 13:24

    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!

    0 讨论(0)
  • 2020-12-28 13:35

    Swift 4:

    let newBoolValue = nsNumberValue.boolValue
    

    0 讨论(0)
  • 2020-12-28 13:42

    NSUserDefaults has two methods to transparently operate with booleans:

    - (BOOL)boolForKey:(NSString *)defaultName

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

    0 讨论(0)
  • 2020-12-28 13:43

    You currently compare two pointers. Use NSNumbers 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) {
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题