objective-c 检查是否设置了 BOOL(不能用 ==nil 完成)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2008682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a BOOL is set (can't be done with ==nil)
提问by Alon Amir
how do i check if a BOOL is set in objective-c (iphone)?
我如何检查在objective-c(iphone)中是否设置了BOOL?
i know that it can be done with an int or float this way: NSNumber *Num = [prefs floatForKey:@"key"]; for example
我知道它可以用 int 或 float 这种方式完成: NSNumber *Num = [prefs floatForKey:@"key"]; 例如
回答by Dave DeLong
You can't. A BOOLis either YESor 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 NSNumberitself is nil. Or have a second BOOLto indicate if you've altered the value of the first.
你不能。ABOOL是YES或NO。没有其他状态。解决这个问题的方法是使用NSNumber( [NSNumber numberWithBool:YES];),然后检查NSNumber它本身是否是nil。或者有第二个BOOL来表明您是否更改了第一个的值。
回答by TechZen
Annoyingly, Objective-C has no Boolean class. It certainly feels like it should and that trips a lot of people up. In collections and core data, all bools are stored as NSNumber instances.
令人讨厌的是,Objective-C 没有 Boolean 类。这当然感觉应该是这样,这让很多人感到震惊。在集合和核心数据中,所有 bool 都存储为 NSNumber 实例。
It's really annoying having to convert back and forth all the time.
必须一直来回转换真的很烦人。
回答by oskarko
By default, a bool value is set to 0 in Objective-C, so you don't need to check if your bool value is nil anytime.
默认情况下,Objective-C 中的 bool 值设置为 0,因此您无需随时检查您的 bool 值是否为零。
回答by Renetik
You can use something like this instead...
你可以用这样的东西来代替......
@import Foundation;
@interface CSBool : NSObject
+ (CSBool *)construct:(BOOL)value;
@property BOOL value;
@end
#import "CSBool.h"
@implementation CSBool
+ (CSBool *)construct:(BOOL)value {
CSBool *this = [self new];
this.value = value;
return this;
}
@end

