Objective-C 第一个小程序

示例一 (类似C)

//1.代码编写
//跟C语言一样,OC程序的入口依然是main函数,只不过写到一个.m文件中.比如这里写到一个main.m文件中(文件名可以是中文)
#include <stdio.h>
int main() {
    printf("Hello world\n");
    return 0;
}

//2.终端指令
cc -c main.m //编译
cc main.o //链接
./a.out //运行

示例二 (不同C)

//1.代码编写
//跟C语言不一样的,使用NSLog函数输出内容
#import <Foundation/Foundation.h>
int main() {
    NSLog(@"Hello world");
    return 0;
}

//2.终端指令
cc -c main.m //编译
cc main.o -framework Foundation //链接
./a.out //运行

3.NSLogprintf的区别

NSLog接收OC字符串作为参数,printf接收C语言字符串作为参数

NSLog输出后会自动换行,printf输出后不会自动换行

使用NSLog需要#import <Foundation/Foundation.h>

使用printf需要#include <stdio.h>

4.#inprot的作用 

跟#include一样,用来拷贝某个文件的内容

可以自动防止文件内容被拷贝多次,也就意味着头文件中不用加入下面的预处理指令了 

#ifndef _STDIO_H_

#define _STDIO_H_

#endif

5.Foundation框架的作用

开发OC, iOS, Mac程序必备的框架

此框架中包含了很多常用的API

框架中包含了很多头文件,若想使用整个框架的内容,包含它的主头文件即可

#import <Foundation/Foundation.h>

6.BOOL的使用

BOOL类型的本质

typedef signed char BOOL;

BOOL类型的变量有2种取值: YES/NO

#define YES (BOOL) 1

#define NO (BOOL) 0

BOOL的输出(当做整数来用)

NSLog(@"%d %d"YESNO);

示例三 (多文件开发)

1.多个.m文件的开发

//跟C语言中多个.c文件的开发是一样的
//编写3个文件
main.m
#import "one.h"
int main(){
    test();
    return 0;
}

one.h
void test();

one.m
#import <Foundation/Foundation.h>
void test(){
    NSLog(@"调用了test函数");
}

//终端指令
cc -c main.m test.m //编译
cc main.o test.o -framework Foundation //链接
./a.out //运行

2..m文件和.c文件混合开发

//编写3个文件
main.m
#import "one.h"
int main(){
    test();
    return 0;
}

one.h
void test();

one.c
#include <stdio.h>
void test(){
    printf("调用了test函数\n");
}

终端指令
cc -c main.m test.m //编译
cc main.o test.o //链接 没有使用Foundation框架的话,就不用-framework Foundation
./a.out //运行

 

posted @ 2015-06-19 16:33  梦三  阅读(2527)  评论(0编辑  收藏  举报