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.
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 .
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.
(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 { .... }
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.
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.
I think you will need to use some class for that, e.g. wrap bool to NSNumber
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With