学习Objective-C的布尔类型

来源:互联网 发布:怎么样推广淘宝店铺 编辑:程序博客网 时间:2024/06/04 19:51

1 .Objective-C也提供了一个相似的类型BOOL,它具有YES和NO两个值。(C语言拥有布尔数据类型bool,它具有true和false两个值)

2. 下面是例子

////  main.m//  BOOL Party////  Created by josephvitt on 2017/6/29.//  Copyright © 2017年 josephvitt. All rights reserved.//#import <Foundation/Foundation.h>//return NO if the two integers have the same//value,YES otherwiseBOOL areIntsDifferent(int thing1,int thing2){    if (thing1 == thing2) {        return (NO);    }else{        return (YES);    }}//areIntsDifferent//given a NO value ,return the human-readable//string "NO" .otherwise return "YES"NSString *boolstring(BOOL yesNo){    if(yesNo == NO){        return(@"NO");    }else{        return (@"YES");    }}//boolstringint main(int argc, const char * argv[]) {    BOOL areTheyDifferernt;    //areTheyDifferernt = areIntsDifferent(5, 5);    areTheyDifferernt = areIntsDifferent(23, 42);        NSLog(@"are %d and %d different? %@",5,5,boolstring(areTheyDifferernt));    return 0;}





【注意⚠️】有时候有经验的c语言程序猿也许会尝试将areIntsDifferent()函数写成一行,

BOOL areIntsDifferent_faulty(int thing1,int thing2){    return (thing1-thing2);}//areIntsDifferent_faulty
之所以这样做是因为假定了非零的值等于YES。但事实并非如此。确实,在C语言中此函数的返回值回事true或者false(0假非零为真);

但是在Objective-C中调用此函数返回的BOOL值只有YES或NO两个。

如果thing1=23,thing2=5,  这样调用函数23-5=18,此函数会报错?因为Objective-C中它并不是等于YES(YES的值以整型表示为1);C中可能会等于真值。

所以,不要将BOOL值和YES直接比较。直接与NO比较一定是安全的,因为C语言中的假值就只有一个0。


还有NSlog()中的说明符%@接受 NNString 字符串类型

原创粉丝点击