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.
我应该如何获得一个bool值我可以在Objective-C中赋给true, false和nil ?Objective-C是什么意思?就像c#可以为空。
I'm looking to be able to use the nil value to represent undefined.
我想用nil值来表示未定义的。
2 个解决方案
#1
28
An NSNumber
instance might help. For example:
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
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.
在10.3之后的所有Mac OS X平台和所有iPhone OS平台上,-[NSNumber boolValue]方法保证返回YES或NO。
#2
1
I think you will need to use some class for that, e.g. wrap bool to NSNumber
object.
我认为您需要使用一些类,例如将bool包装到NSNumber对象。
#1
28
An NSNumber
instance might help. For example:
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
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.
在10.3之后的所有Mac OS X平台和所有iPhone OS平台上,-[NSNumber boolValue]方法保证返回YES或NO。
#2
1
I think you will need to use some class for that, e.g. wrap bool to NSNumber
object.
我认为您需要使用一些类,例如将bool包装到NSNumber对象。