Objective-c学习笔记—— 基础内容

本文介绍Objective-C中的基本概念,包括布尔值处理、变量与循环、字符串操作及文件读取等,通过实例展示如何进行简单的程序编写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BOOL

   首先编写程序:

#import <Foundation/Foundation.h>

BOOL areIntDifferent(int ver1 , int ver2){
        if(ver1 == ver2){
                return (NO);
        }else{
                return (YES);
        }
}

NSString* boolString(BOOL yesNo){
        if(yesNo == NO){
                return (@"NO");
        }else{
                return (@"YES");
        }
}

int main(int argc , const char *argv[]){
        BOOL isDiff;
        isDiff = areIntDifferent(6,6);
        NSLog(@"are %d and %d different ? %@" , 6,6,boolString(isDiff));
        isDiff = areIntDifferent(29,48);
        NSLog(@"are %d and %d different ? %@" , 29,48,boolString(isDiff));
        return (0);
}
   然后在相同目录编写GNUMakefile文件
include $(GNUSTEP_ROOT)/common.make

TOOL_NAME = CompareTwoNum
CompareTwoNum_OBJC_FILES = compare.m

include $(GNUSTEP_ROOT)/tool.make

执行命令:

make  编译成功  , 执行文件   ./obj/CompareTwoNum , 输出如下结果:

2014-05-06 05:26:58.665 CompareTwoNum[3277] are 6 and 6 different ? NO
2014-05-06 05:26:58.666 CompareTwoNum[3277] are 29 and 48 different ? YES

注意事项:1、在areIntDifferent函数中不要使用 以下语句替代函数中的内容

                       return ver1 - ver2 ;

                                         2、 不要用BOOL 值和 YES 比较 , 和NO比较一定安全。(OBJC中1不等于YES)


变量 + 循环

#import <Foundation/Foundation.h>

int main(int argc , const char *argv[]){
        int count = 3 ;
        NSLog(@"the number from 0 to %d is : ",count);
        int i ;
        for(i = 0 ; i <= count  ; i++){
                NSLog(@"%d ", i);
        }
        return (0);
}
GNUMakefile 文件内容参见上文。


字符串操作 + strlen (求字符串长度函数)

#import <Foundation/Foundation.h>

int main(int argc , const char * argv[]){
        const char * words[4] = {"hello" , "zhangting" , "latitude" , "longitude"};
        int count = 4 ;
        int i ;
        for(i = 0 ; i < count ; i++){
                NSLog(@"the length of %s is %d" , words[i] , strlen(words[i]));
        }
        return 0;
}


文件操作 + strlen

#import <Foundation/Foundation.h>

int main(int argc , const char * argv[]){
        FILE * rf = fopen("tmp.txt" , "r");
        char word[256];
        while(fgets(word,256,rf)){
                word[strlen(word) -1] = '\0';
                NSLog(@"The length of %s is %d ." , word , strlen(word));
        }
        fclose(rf);
        return (0);
}
执行该文件之前需准备好文件 tmp.txt

fgets 会连每行的换行符都读取,这样会占用一个字符的长度,所以使用

word[strlen(word) -1] = '\0';
将该换行符替换为字符串结尾符号。


objective-c 中的消息发送表示

[object say]  : 表示向object对象发送say 消息


objective-c 中新术语

方法: 为响应消息而运行的代码。

方法调度程序 :Objective-c 使用的一种用于推测执行什么方法来响应特定的消息。

接口:对象的类应该提供的操作。

实现:使接口正常工作的代码。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值