什么是获得可空的布尔的Objective-C方式?

Gre*_*ton 16 logic types boolean objective-c

我应该如何获得一个bool值,我可以在Objective-C中指定true,false和nil?Objective-C的做法是什么?很像C#的Nullable.

我希望能够使用nil值来表示undefined.

dre*_*lax 31

一个NSNumber实例可能会有所帮助.例如:

NSNumber *yesNoOrNil;

yesNoOrNil = [NSNumber numberWithBool:YES]; // set to YES
yesNoOrNil = [NSNumber numberWithBool:NO];  // set to NO
yesNoOrNil = nil; // not set to YES or NO
Run Code Online (Sandbox Code Playgroud)

为了确定它的价值:

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");
}
Run Code Online (Sandbox Code Playgroud)

在10.3之后的所有Mac OS X平台和所有iPhone OS平台上,该-[NSNumber boolValue]方法保证返回YES或NO.