ObjectC中的BOOL类型

绝不要直接将BOOL值和YES比较

Objective-C中的BOOL实际上是一种带符号的的字符类型(signed char)的定义,它使用8位存储空间。YES定义为1,而NO定义为0.

  1. #import <Foundation/Foundation.h>
  2. BOOL areIntsDifferent(int things1, int things2)
  3. {
  4. if(things1 == things2)
  5. return (NO);
  6. else
  7. return (YES);
  8. }//areIntsDifferent
  9. NSString *boolString(BOOL yesNo)
  10. {
  11. if (yesNo == NO)
  12. return (@"NO");
  13. else {
  14. return (@"YES");
  15. }
  16. }
  17. int main(int argc, const char *argv[])
  18. {
  19. BOOL areTheyDifferent;
  20. areTheyDifferent = areIntsDifferent(5, 5);
  21. NSLog(@"are %d and %d different? %@", 5, 5, boolString(areTheyDifferent));
  22. areTheyDifferent = areIntsDifferent(23, 24);
  23. NSLog(@"are %d and %d different? %@", 23, 24, boolString(areTheyDifferent));
  24. return 0;
  25. }

这是一段很简单的代码,很容易得到如下结果:

注意到上面我们说了YES其实是1 ,并不是非零,将代码改变如下

  1. #import <Foundation/Foundation.h>
  2. BOOL areIntsDifferent(int things1, int things2)
  3. {
  4. /*
  5. if(things1 == things2)
  6. return (NO);
  7. else
  8. return (YES);
  9. */
  10. int diff = things1 - things2;
  11. if (diff == YES)
  12. return (YES);
  13. else
  14. return (NO);
  15. }//areIntsDifferent
  16. NSString *boolString(BOOL yesNo)
  17. {
  18. if (yesNo == NO)
  19. return (@"NO");
  20. else {
  21. return (@"YES");
  22. }
  23. }
  24. int main(int argc, const char *argv[])
  25. {
  26. BOOL areTheyDifferent;
  27. areTheyDifferent = areIntsDifferent(5, 5);
  28. NSLog(@"are %d and %d different? %@", 5, 5, boolString(areTheyDifferent));
  29. areTheyDifferent = areIntsDifferent(23, 24);
  30. NSLog(@"are %d and %d different? %@", 23, 24, boolString(areTheyDifferent));
  31. return 0;
  32. }

在C语言中,默认非0就是yes,但是从上面的代码可以看出,23-24 == -1,此时应该返回YES的,但是运行结果如下:

主要原因是Objective-C中YES被define为1,并不是非0,在代码的编写过程中,这一点一定要注意。





原文地址:https://www.cnblogs.com/const-zhou/p/4425015.html