绝不要直接将BOOL值和YES比较
Objective-C中的BOOL实际上是一种带符号的的字符类型(signed char)的定义,它使用8位存储空间。YES定义为1,而NO定义为0.
#import <Foundation/Foundation.h>
BOOL areIntsDifferent(int things1, int things2)
{
if(things1 == things2)
return (NO);
else
return (YES);
}//areIntsDifferent
NSString *boolString(BOOL yesNo)
{
if (yesNo == NO)
return (@"NO");
else {
return (@"YES");
}
}
int main(int argc, const char *argv[])
{
BOOL areTheyDifferent;
areTheyDifferent = areIntsDifferent(5, 5);
NSLog(@"are %d and %d different? %@", 5, 5, boolString(areTheyDifferent));
areTheyDifferent = areIntsDifferent(23, 24);
NSLog(@"are %d and %d different? %@", 23, 24, boolString(areTheyDifferent));
return 0;
}
这是一段很简单的代码,很容易得到如下结果:
注意到上面我们说了YES其实是1 ,并不是非零,将代码改变如下
#import <Foundation/Foundation.h>
BOOL areIntsDifferent(int things1, int things2)
{
/*
if(things1 == things2)
return (NO);
else
return (YES);
*/
int diff = things1 - things2;
if (diff == YES)
return (YES);
else
return (NO);
}//areIntsDifferent
NSString *boolString(BOOL yesNo)
{
if (yesNo == NO)
return (@"NO");
else {
return (@"YES");
}
}
int main(int argc, const char *argv[])
{
BOOL areTheyDifferent;
areTheyDifferent = areIntsDifferent(5, 5);
NSLog(@"are %d and %d different? %@", 5, 5, boolString(areTheyDifferent));
areTheyDifferent = areIntsDifferent(23, 24);
NSLog(@"are %d and %d different? %@", 23, 24, boolString(areTheyDifferent));
return 0;
}
在C语言中,默认非0就是yes,但是从上面的代码可以看出,23-24 == -1
,此时应该返回YES的,但是运行结果如下:
主要原因是Objective-C中YES被define为1,并不是非0,在代码的编写过程中,这一点一定要注意。
时间: 2024-10-07 02:28:18