Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a BOOL is set (can't be done with ==nil)

how do i check if a BOOL is set in objective-c (iphone)?

i know that it can be done with an int or float this way: NSNumber *Num = [prefs floatForKey:@"key"]; for example

like image 398
Alon Amir Avatar asked Jan 05 '10 19:01

Alon Amir


People also ask

Can bool be nil?

You can't. A BOOL is either YES or NO . There is no other state.

Can bool be nil Swift?

Nil is not a Bool. phoneyDev: The error states that the Bool? has not been unwrapped. That's what optional chaining does.

How do you know if boolean is optional?

Optional binding The code let booleanValue = booleanValue returns false if booleanValue is nil and the if block does not execute. If booleanValue is not nil , this code defines a new variable named booleanValue of type Bool (instead of an optional, Bool? ).

How do you know if a boolean is real?

To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean. Copied!


2 Answers

You can't. A BOOL is either YES or NO. There is no other state. The way around this would be to use an NSNumber ([NSNumber numberWithBool:YES];), and then check to see if the NSNumber itself is nil. Or have a second BOOL to indicate if you've altered the value of the first.

like image 157
Dave DeLong Avatar answered Oct 11 '22 18:10

Dave DeLong


Annoyingly, Objective-C has no Boolean class. It certainly feels like it should and that trips a lot of people up. In collections and core data, all bools are stored as NSNumber instances.

It's really annoying having to convert back and forth all the time.

like image 35
TechZen Avatar answered Oct 11 '22 18:10

TechZen