在objc.h 中,BOOL 定义为:
- typedef signed char BOOL;
- #define YES (BOOL) 1
- #define NO (BOOL) 0
- BOOL enabled = NO;
- enabled = 0;
- if(enabled == YES){
- }
- if(enabled){
- }
- if(!enabled){
- }
- if(enabled != YES){
- }
判断一个数是否是质数,是就返回YES,不是则返回NO。
- - (BOOL)isPrime:(int num){//算法请读者自己去琢磨,看不懂需要解释的请留言
- for( int i = 2; i< num/2 ; i++){
- if( num%i == 0){
- return NO;
- }
- }
- return YES;
- }
BOOL的值,只取最高位做判断,比如,5的2进制是0x101,对BOOL来说是YES,4的2进制是0x100,对BOOL来说是NO
不过好像指针不用遵守这个规则
bool的值,直接取0和非0。
boolean_t t1 = 1;//int type
Boolean t2 = 1; //unsigned char type
BOOL t3 = 4;//YES or NO
bool t4 = 1;//true or false
NSAssert(t1, @"boolean_t t1 is NO");//通过测试
NSAssert(t2, @"boolean_t t2 is NO");//通过测试
NSAssert(t3, @"boolean_t t3 is NO");//通过测试
NSAssert(t4, @"boolean_t t4 is NO");//通过测试
说明:objective-c 中的BOOL 实际上是一种对带符号的字符类型(signed char)的类型定义(typedef),它使用8位的存储空间。通过#define指令把YES定义为1,NO定义为0。
注意:objective-c 并不会将BOOL作为仅能保存YES或NO值的真正布尔类型来处理。编译器仍将BOOL认作8位二进制数,YES 和 NO 值只是在习惯上的一种理解。
问题:如果不小心将一个大于1字节的整型值(比如short或int)赋给一个BOOL变量,那么只有低位字节会用作BOOL值。如果该低位字节刚好为0(比如8960,写成十六进制为0x2300),BOOL值将会被认作是0,即NO值。而对于bool类型,只有true和false的区别,即0为false,非0为true。
举例:
BOOL b1=8960; // 实际是 NO,因为8960换成十六进制为0x2300,BOOL 只有8位存储空间,取0x2300的低8位,00,所以是NO
bool b2=8960;//实际是true,因为bool类型,非0即为true。