iOS预编译头文件_PCH

2017-02-22  本文已影响147人  iOS收藏家

PCH--预编译头文件

全称 (Precompiled Header) 程序设计时将头文件编译为中间格式,以节约开发过程中反复编译该头文件的开销。在开发过程中直接使用头文件的内容而不需要在去引用头文件,这样很大程度上带来了编程的便利性,提高效率。(中间形式称为预编译头文件)

Q:为什么在XCode 6 版本之后创建工程ProjectName-Prefix.pch 默认取消了?

A:认可的答案是说怀疑工程模块化的原因。(个人理解是因为PCH文件的引入导致文件模块间依赖性比较大,耦合程度比较高)。

对于那些全局都用到的文件可以引用到PCH文件中。如宏定义,可以先定义在一个文件中,然后在PCH中在引用文件。如果有一些必要的但是很大的文件引入到PCH中,你就要重新考虑一下你的工程架构。

⚠️例如HUD在你的每个控制器中都会使用到,你应该在每个控制中引入HUD直接使用。当你把这个控制器移植到你另一个项目中时,你会很清楚的知道哪些文件需要引入。这一点对于类别来讲尤为重要。假如文件是隐式引入的,对于文件复用的话就会很苦难。

⚠️PCH文件不会为了解决避免文件依赖关系。必要的时候要像Xcode 模版那样引入UIKit.h 或者 Foundation.h。PCH文件的目的是为了提高编译大文件的处理时间。

原文如下:


I suspect because of modules, which remove the need for 
the #import <Cocoa/Cocoa.h>.

As to where to put code that you would put in a prefix header,
 there is no code you should put in a prefix header.
Put your imports into the files that need them. 
Put your definitions into their own files. Put your macros...nowhere. 
Stop writing macros unless there is no other way (such as when you need __FILE__). 
If you do need macros, put them in a header and include it.

The prefix header was necessary for things that are huge and
used by nearly everything in the whole system (like Foundation.h).
If you have something that huge and ubiquitous, you should rethink 
your architecture. 
Prefix headers make code reuse hard, and introduce subtle build problems
if any of the files listed can change. 
Avoid them until you have a serious build time problem that you can 
demonstrate is dramatically improved with a prefix header.

In that case you can create one and pass it into clang, but it's incredibly 
rare that it's a good idea.

EDIT: To your specific question about a HUD you use in all your view 
controllers, yes, you should absolutely import it into every view controller that 
actually uses it.
This makes the dependencies clear. When you reuse your view controller in 
a new project (which is common if you build your controllers well), you will 
immediately know what it requires.
This is especially important for categories, which can make code very hard to 
reuse if they're implicit.

The PCH file isn't there to get rid of listing dependencies.
You should still import UIKit.h or Foundation.h as needed, as the Xcode 
templates do. The reason for the PCH is to improve build times when dealing 
with really massive headers (like in UIKit).

手动添加PCH文件

1、在Xcode中我们可以通过 New file -> Other-> PCH file 添加PCH文件

2、setting->prefix header->path 设置PCH的路径 ($(SRCROOT)/filename.pch) 如下:

PCH_path.png

关于Precompile Prefix Header

Precompile Prefix Header 设置为YES,PCH文件会被预编译处理,预编译后的文件会被缓存起来,从而提高编译速度。

查看编译日志截图:

YES.jpeg

⚠️如果Precompile Prefix Header为NO,那么每个引用了pch内容的.m文件都要编译一次pch。

查看编译日志截图:

VCNO.jpeg LoginNo.jpeg

参考地址如下:

cocoachina 维基百科stackoverflow

上一篇下一篇

猜你喜欢

热点阅读