How to convert and compare NSNumber with BOOL?

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

  • How to convert back from NSNumber to BOOL?
  • How to compare the value of NSNumber with BOOL.

I currently have:

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

is there any better way to compare?

Thank!

+50
objective-c iphone
Mar 19 '10 at 16:41
source share
4 answers

You are currently comparing two pointers. Instead, use the NSNumber methods to actually compare them:

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

To get the bool value from NSNumber , use -(BOOL)boolValue :

 BOOL b = [num boolValue]; 

With this comparison will be easier to read for me this way:

 if([num boolValue] == NO) { // ... } 
+137
Mar 19 '10 at 16:43
source share

NSUserDefaults has two methods for transparently handling booleans:

- (BOOL)boolForKey:(NSString *)defaultName

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

+1
Jul 09 '13 at 17:38
source share

The only way I was able to extract the booleanity NSNumber from its NSConcreteValue (doh!) Was as follows:

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

Every trick ... FAILED . Buyer beware, this is not reliable ( __NSCFNumber may very well be platform / machine specific - these are only details of Apple's implementation) ... but as they say, nothing else worked!

0
Feb 19 '14 at 11:17
source share

Swift 4:

 let newBoolValue = nsNumberValue.boolValue 

enter image description here

0
Sep 06 '19 at 10:17
source share



All Articles