本帖最后由 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
- #import <Foundation/Foundation.h>
- NSString* test(BOOL bol)
- {
- if(bol == YES)
- {
- return @"111";
- }else
- return @"000";
- }
- int main()
- {
- BOOL bo = NO;
- NSLog(@"%d",bo);
- NSLog(@"%@",test(YES));
- NSLog(@"%@",test(bo));
- return 0;
- }
复制代码
BOOL小程序2
- #import <Foundation/Foundation.h>
- //比较两个数 相等返回NO
- BOOL areIntsDifferent(int num1, int num2)
- {
- if(num1 == num2){
- return (NO);
- }else{
- return (YES);
- }
- }
- //将BOOL类型 转换为字符串类型
- NSString *boolString(BOOL yesNo)
- {
- if(yesNo == NO){
- return (@"NO");
- }else{
- return (@"YES");
- }
- }
- int main(int argc, const char * argv[])
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
-
- BOOL bo;
- bo = areIntsDifferent(5,5);
- NSLog(@"bool:%@",boolString(bo));
- bo = areIntsDifferent(2,3);
- NSLog(@"bool:%@",boolString(bo));
- NSLog(@"%@",boolString(bo));
-
- [pool drain];
-
- return 0;
- }
复制代码 细节问题1:
如果一不小心将一个长于1字节的整型(例如short或int值)赋值给一个BOOL变量,那么只有低位字节会作用BOOL值。家是将整数 8960 赋值 BOOL类型,BOOL 值将会是0,即NO值。
范例:
- #import <Foundation/Foundation.h>
- int main(int argc, const char * argv[])
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
- BOOL bol = YES;
- //赋值前
- NSLog(@"bol = %d",bol);
- bol = bol = 8960;
- //赋值后
- NSLog(@"bol = %d",bol);
- [pool drain];
- return 0;
- }
复制代码
|
|