Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 445
Jakub Avatar asked Mar 19 '10 16:03

Jakub


People also ask

How to convert NSNumber to BOOL?

To get the bool value from a NSNumber use -(BOOL)boolValue : BOOL b = [num boolValue];

What is NSNumber?

Overview. NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char , short int , int , long int , long long int , float , or double or as a BOOL .


2 Answers

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) {     // ... } 
like image 97
Georg Fritzsche Avatar answered Sep 22 '22 17:09

Georg Fritzsche


Swift 4:

let newBoolValue = nsNumberValue.boolValue 

enter image description here

like image 22
alegelos Avatar answered Sep 22 '22 17:09

alegelos