今天开始了学习Objective-C 自己总结下以后需要注意的问题~~菜鸟级请大神指教


问题注意一、布尔类型(BOOL)

首先附上学习使用的代码:main.h

------------------------------------------------------------------------------------------------------------------------------------------

//

//  main.m

//  Helio objective-c

//

//  Created by 女程序猿 on 15/5/17.

//  Copyright (c) 2015 女程序猿. All rights reserved.

//


#import <Foundation/Foundation.h>



    //returns no is teo integers have the same

    //value,yes otherwise

    BOOL areIntsDifferent(int thing1,int thing2)

    {

        if(thing1==thing2){

            return (NO);

        }

        else{

            return (YES);

        }

    }//areIntsDifferent

    //given a No value,return the human-readable

    //string "NO".Itherwise return "YES"

    

    NSString *boolString(BOOL yesNo)

    {

        if (yesNo == NO) {//BOOL

            return (@"NO");

        }else{

            return (@"YES");

        }

    }//boolString

    int main(int argc, const char *argv[])

    {

        BOOL areTheyDifferent;

        areTheyDifferent = areIntsDifferent(5, 5);

        NSLog(@"ARE %d and %d different? %@",5,5,boolString(areTheyDifferent));

        

        areTheyDifferent = areIntsDifferent(23, 42);

        NSLog(@"ARE %d and %d different? %@",23,42,boolString(areTheyDifferent));

        return 0;

        

    }

------------------------------------------------------------------------------------------------------------------------------------------

获取BOOL值时要注意方法

想来大部分初步接触Objective-C并且有一定C语言基础的人在进行areIntsDifferent()的编写时可能会把函数写成一行语句

    BOOL areIntsDifferent_faulty(int thing1,int thing2)

    {

        return(thing1 - thing2)

    }//areIntsDifferent_faulty

这样做的原因时假定非零值等于YES。但事实并不是如此。的确在c语言中会返回的是true或者false,但是在中Objective-C返回的BOOL值只有YES或NO

    if(areIntsDifferent_faulty(23,5)==YES) {

    //...

    }

在c语言中返回的值返回的值可能等同于真值,但是在Objective-C中由于YES的值以整数型为1,而23-5=18并不等于1所以函数将显示错误

!!!因此BOOL值尽量不要与YES进行比较

将之前的if语句改成

    if(areIntsDifferent_faulty(23,5)) {

        //...

        }

就正确了。

直接与NO比较一定是安全的,因为c语言中的假值就一个0.


注:参考书籍:Objective-C基础教程 人民邮电出版社