Objective-c – How to convert and compare NSNumber to BOOL

iphoneobjective c

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!

Best Answer

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) {
    // ...
}