object-c中的布尔类型比C语言中的bool类型早了10年,它具有YES和NO两种值。在object-c中的布尔类型BOOL实际上是一种带符号的字符类型(signed char),它使用的空间是1byte,即8bit,其中YES定义为1,NO定义为0。将大于1字节的整形数(比如short或者int)赋给BOOL变量,会被截断处理,只保留末尾的8个bit。
以下是object-c中使用BOOL类型的例子:
#import <Foundation/Foundation.h> //比较两个int数是否一样 BOOL areINTsDifferent(int thing1,int thing2){ if(thing1==thing2) return NO; else return YES; } //返回BOOL类型的数对应的NSString字符串 NSString * boolString(BOOL yesNo){ if(yesNo==YES) return @"YES"; else return @"NO"; } int main(int argc, const char * argv[]) { BOOL areTheyDifferent ; areTheyDifferent= areINTsDifferent(6,6); //下面的%@表示NSString占位符 NSLog(@"are %d and %d different? %@",6,6,boolString(areTheyDifferent)); areTheyDifferent = areINTsDifferent(23,42); NSLog(@"are %d and %d different? %@",23,42,boolString(areTheyDifferent)); return 0; }
输出的结果:
2016-04-04 23:18:48.964 hello-obj[1267:84194] are 6 and 6 different? NO 2016-04-04 23:18:48.965 hello-obj[1267:84194] are 23 and 42 different? YES
时间: 2024-10-09 02:26:28