What is the Objective-C way of getting a nullable bool?
10,270
Solution 1
An NSNumber
instance might help. For example:
NSNumber *yesNoOrNil;
yesNoOrNil = [NSNumber numberWithBool:YES]; // set to YES
yesNoOrNil = [NSNumber numberWithBool:NO]; // set to NO
yesNoOrNil = nil; // not set to YES or NO
In order to determine its value:
if (yesNoOrNil == nil)
{
NSLog (@"Value is missing!");
}
else if ([yesNoOrNil boolValue] == YES)
{
NSLog (@"Value is YES");
}
else if ([yesNoOrNil boolValue] == NO)
{
NSLog (@"Value is NO");
}
On all Mac OS X platforms after 10.3 and all iPhone OS platforms, the -[NSNumber boolValue]
method is guaranteed to return YES or NO.
Solution 2
I think you will need to use some class for that, e.g. wrap bool to NSNumber
object.
Related videos on Youtube
Comments
-
The4thIceman almost 4 years
How should I go about getting a bool value that I can assign true, false and nil to in Objective-C? What is the Objective-C way of doing this? Much like C#'s Nullable.
I'm looking to be able to use the nil value to represent undefined.
-
Carlos P over 10 yearsAgreed that this is the closest way of doing it natively, but I hate having to do it this way. It leads to hard-to-spot bugs if a dev forget that the property is an
NSNumber*
and assumes it's aBOOL
, in which case they test forif (yesNoOrNil)
and it gives incorrect results without any warning.