OBjective-C中的 #include与#import的区别以及#define的用法

来源:互联网 发布:三砖淘宝店铺 编辑:程序博客网 时间:2024/05/18 01:29

#include 和#import都是先要求预处理器读取某个文件,然后将读入的内容添加至输出结果。 通常使用这两个指令来导入头文件(.h文件)。

两者的差别:

#import会确保预处理器只导入特定的文件一次。

#include则允许多次导入同一个文件.

文件名加上双引号或尖括号. 如果是双引号,那么编译器会先在项目目录下查找相应的头文件。如果是尖括号,那么编译器会先在预先设好的标准目录下查找相应的头文件。

例如:

//导入项目中的Person.h头文件

#import "Person.h"

#import <Foundation/Foundation.h>

#import "Person.h"


//导入标准库的头文件

#import <ldap.h>

#include <CoreFoundation/CoreFoundation.h>

#import <Foundation/NSObjCRuntime.h>

#import <Foundation/NSArray.h>

#import <Foundation/NSAutoreleasePool.h>

#import <Foundation/NSBundle.h>

#import <Foundation/NSByteOrder.h>

#import <Foundation/NSCalendar.h>

#import <Foundation/NSCharacterSet.h>

#import <Foundation/NSCoder.h>

#import <Foundation/NSData.h>


#include <sys/types.h>

#include <stdarg.h>

#include <assert.h>

#include <ctype.h>

#include <errno.h>

#include <float.h>

#include <limits.h>

#include <locale.h>

#include <math.h>

#include <setjmp.h>

#include <signal.h>

#include <stddef.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <time.h>


#define 告诉编译器: 在编译器看到A之前,使用B替换之。以Math.h中的PI作为一个例子:

A 就是M_PI, B就是3.14159265358979323846264338327950288

#define M_PI        3.14159265358979323846264338327950288  /* pi             */


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

    @autoreleasepool {


        NSLog(@"\u03c0 is %f",M_PI);


    }

    return 0;

}


输出:

2017-12-16 19:38:14.918961+0800 learnOCBasicClassh[11424:6060101] π is 3.141593

Program ended with exit code: 0


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

    @autoreleasepool {


        NSLog(@"\u03c0 is %2.5f",M_PI);

        NSLog(@"%d is larger",MAX(20, 45));

    }

    return 0;

}



2017-12-16 19:47:04.318326+0800 learnOCBasicClassh[11977:6087195] π is 3.14159

2017-12-16 19:47:04.318609+0800 learnOCBasicClassh[11977:6087195] 45 is larger

Program ended with exit code: 0


MAX(A,B) 是一个#define指令。

#define MAX(A,B)((A) > (B)? (A) : (B))

当编译器处理以上代码时,其处理过程应该是下面代码:

NSLog(@"%d is larger", ((20) > (45)? (20) :(45)));

通过#define,不仅可以替换代码中的某个特定值,还可以构建类似函数的代码段。后者的这类类似函数的代码段称为宏(macro).