.pch文件是precompiled header,从文字上理解就是预编译头文件,首先说下这类文件有什么作用吧
1.这个文件中可以定义整个工程使用到的全局变量或全局宏,具体文件中就不需要再定义。
2.这个文件中也可以定义整个工程中使用的.h文件统一import进来,具体调用的文件中就不需要import
这个文件给我们带来了很大的方便,但在.pch中import进来的文件和定义的变量、宏对整个工程来说都是完全可见的,会存在一些安全隐患。
有得就有弊,我们在实际开发中根据需要来使用这个文件吧,下面就看看在XCode8.3.1中如何使用
我在XCode8.3.1创建文件时XCode没有自动生成.pch文件,需要自己手动创建
选择pch文件
名称可以使用默认,也可以自定义,这里使用默认名称,并把Targets勾选
工程上就创建了pch文件
按下来是给工程配置pch文件,$(SRCROOT)是当前工程的目录,绝对路径要看你创建的文件放在哪个目录下,根据实际情况填写
编辑和使用pch文件
在pch文件中定义一个全局的宏
//
// PrefixHeader.pch
// FrameworkUtils
//
// Created by dcr on 2017/4/15.
// Copyright © 2017年. All rights reserved.
//
#ifndef PrefixHeader_pch
#define PrefixHeader_pch
// Include any system framework and library headers here that should be included in all compilation units.
// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.
#endif /* PrefixHeader_pch */
//定义全局宏
#define SCREEN_SIZE [UIScreen mainScreen].bounds.size
//import全局使用的头文件
#import "BackView.h"
使用这个宏,就像是本文件中定义的一样。
//
// ViewController.m
// FrameworkUtils
//
// Created by dcr on 2017/4/15.
// Copyright © 2017年. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSLog(@"height = %g, width = %g", SCREEN_SIZE.height, SCREEN_SIZE.width);
NSLog(@"str = %@", [BackView getString]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
打印的结果