A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© wangxiaoit 中级黑马   /  2014-12-14 15:38  /  759 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 wangxiaoit 于 2014-12-14 16:00 编辑

Objective-C BOOL使用
BOOL 类型的本质
        typedef signed char BOOL;
BOOL类型的变量有2中取值: YES,NO
        #define YES (BOOL)1
        #define NO (BOOL)0
BOOL 的输出(当做整数来用)
        NSLog(@"%d  %d",YES,NO);

BOOL小程序1
  1. #import <Foundation/Foundation.h>

  2. NSString* test(BOOL bol)
  3. {
  4.     if(bol == YES)
  5.     {   
  6.         return @"111";
  7.     }else
  8.         return @"000";
  9. }



  10. int main()
  11. {
  12.     BOOL bo = NO;
  13.     NSLog(@"%d",bo);

  14.     NSLog(@"%@",test(YES));
  15.     NSLog(@"%@",test(bo));
  16.     return 0;
  17. }
复制代码


BOOL小程序2
  1. #import <Foundation/Foundation.h>

  2. //比较两个数 相等返回NO
  3. BOOL areIntsDifferent(int num1, int num2)
  4. {
  5.     if(num1 == num2){
  6.         return (NO);
  7.     }else{
  8.         return (YES);
  9.     }   
  10. }
  11. //将BOOL类型 转换为字符串类型
  12. NSString *boolString(BOOL yesNo)
  13. {
  14.     if(yesNo == NO){
  15.         return (@"NO");
  16.     }else{
  17.         return (@"YES");
  18.     }   
  19. }

  20. int main(int argc, const char * argv[])
  21. {
  22.     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
  23.    
  24.     BOOL bo;
  25.     bo = areIntsDifferent(5,5);
  26.     NSLog(@"bool:%@",boolString(bo));
  27.     bo = areIntsDifferent(2,3);
  28.     NSLog(@"bool:%@",boolString(bo));
  29.     NSLog(@"%@",boolString(bo));
  30.    
  31.     [pool drain];
  32.    
  33.     return 0;
  34. }
复制代码
细节问题1:
        如果一不小心将一个长于1字节的整型(例如short或int值)赋值给一个BOOL变量,那么只有低位字节会作用BOOL值。家是将整数 8960 赋值 BOOL类型,BOOL 值将会是0,即NO值。
范例:
  1. #import <Foundation/Foundation.h>


  2. int main(int argc, const char * argv[])
  3. {
  4.     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];

  5.     BOOL bol = YES;
  6.     //赋值前
  7.     NSLog(@"bol = %d",bol);
  8.     bol = bol = 8960;
  9.     //赋值后
  10.     NSLog(@"bol = %d",bol);

  11.     [pool drain];
  12.     return 0;
  13. }
复制代码





0 个回复

您需要登录后才可以回帖 登录 | 加入黑马