Adam Lee
Adam Lee

Reputation: 25778

What's the difference when putting header inside pch file?

In some tutorial, it is said that we can put some header files in the pch file. After that, I still see that the same header are included in the individual header file? why we put the header in the pch file?

For exmaple, UIKit.h

Upvotes: 3

Views: 897

Answers (1)

Khaled Barazi
Khaled Barazi

Reputation: 8741

I believe there are 2 questions here:

  1. Why duplicate the importing of header files in the pch and the individual source files? You are correct, this is redundant and you can easily get rid of one of the duplicated imports and still run your program and still be able to use Xcode's completion help. For example, you can remove UIKit import from either .pch or your View Controller. However, UIKit and UIFoundation are a special case since they are pretty much at the core of Cocoa Touch and this is just how template projects load. And so Apple decided to have them duplicated. This is likely because a developer could decide to get rid of the .pch and so Apple wanted to ensure that every new UIViewController would work right out of the gate since it would automatically import UIKit. But for all other Frameworks/classes that you add, you only need to put it in one place (.pch file or individual source file that is importing it). This leads to the second question:

  2. When to use .pch (versus regular import in a source file)? Pre-compiled headers, especially during building (compiling) your app, can be very useful as the headers in the .pch file are only compiled the first time and then only if the headers change in the future. If your app imports many frameworks/headers that do not change; this could accelerate building (compiling) since the compiler will use the .pch versus compiling every imported framework/class every time you compile.

PS: Regardless whether you import frameworks/classes in the .pch file or in individual classes; you still need to link the relevant framework/library in the project since that is where the code is versus the public header which just helps you write code that uses the public properties/variables and methods of that class/framework. UIKit and foundation frameworks are linked by default.

PS2: As .pch file states, any headers listed in .pch will be imported to all source files. You might think this is redundant but the usage of #import eliminates any redundant imports.

Hope this helps

Upvotes: 2

Related Questions