In the previous versions of Xcode, a PCH file will be automatically added into your project upon creation. A PCH (precompiled header) file enables you to import certain headers into all your classes, so that you do not have to manually add them into all of them. This saves a lot of hassle and creates cleaner code (it can also save build time). I have to caution though, that we have to avoid importing ALL header files into ALL classes.
I create a Constants.h
file to store my number and string constants for use in my classes, so I have to import it into almost every class. In this case, a PCH file will come in good use.
First, go to File > New > File...
:
On the left pane, select Other
under iOS
. Select PCH File
on the right pane.
Save your file in your project folder (let’s say your file name is “MyPrefixHeader.pch”).
Next, go to your Target’s Build Settings
.
- Change the value in
Prefix Header
to the location of your PCH file (e.g. my project folder isLuvelle Codes
, so the location of my PCH file isLuvelle Codes/MyPrefixHeader.pch
). - Also change the value in
Precompile Prefix Header
to YES.
Now, add import statements into your PCH file!
// // PrefixHeader.pch // Luvelle Codes // // Created by Michelle Teo on 12/1/15. // Copyright (c) 2015 Michelle Teo. All rights reserved. // #ifndef Luvelle_Codes_PrefixHeader_pch #define Luvelle_Codes_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. #import "Constants.h" #endif
[…] Note: If you have to access Constants.h in almost all your classes, it makes little sense to repeatedly add the import "Constants.h" statement in all of them. Follow the instructions under this post to import them conveniently using a PCH file. […]