在 Objective-C 中,我应该如何获取可以分配 true、false 和 nil 的 bool 值?这样做的 Objective-C 方法是什么?很像 C# 的 Nullable。
我希望能够使用 nil 值来表示未定义。
最佳答案
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
为了确定它的值(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");
}
在 10.3 之后的所有 Mac OS X 平台和所有 iPhone OS 平台上,-[NSNumber boolValue]
方法保证返回 YES 或 NO。
关于objective-c - 获取可为空的 bool 的 Objective-C 方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3456576/