views:

70

answers:

3

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 be able to use the nil value to represent undefined.

+1  A: 

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

Vladimir
+1 You certainly don't *need* to use a class, but it's the best way.
walkytalky
+3  A: 

You could use an enum which defines TRUE, FALSE and UNDEFINED.

To be honest, it's not a good idea to have a bool which can hold three states.

Emiswelt
+1  A: 

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.

dreamlax