Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Objective-C way of getting a nullable bool?

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.

like image 924
Greg Sexton Avatar asked Aug 11 '10 08:08

Greg Sexton


People also ask

Can bool be null in Objective C?

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 .

What is a nullable bool?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.

How do you check if a Boolean is nullable?

(a ?: b) is equivalent to (if (a != null) a else b). So checking a nullable Boolean to true can be shortly done with the elvis operator like that: if ( a ?: false ) { ... } else { .... }

How do you make a Boolean nullable in C#?

Amongst other, more important distinctions, value types, such as bool or int, cannot contain null values. You can, however, use nullable version of value types. bool? is a C# alias for the . NET Nullable<bool> type (in the same way string is an alias for String ) and can contain null values.


2 Answers

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.

like image 66
dreamlax Avatar answered Oct 11 '22 12:10

dreamlax


I think you will need to use some class for that, e.g. wrap bool to NSNumber object.

like image 28
Vladimir Avatar answered Oct 11 '22 14:10

Vladimir