arm1.ru

A Useful Thing: Prefix.pch

I discovered a useful thing in iOS development: the Prefix.pch file, a Precompiled Header.

From the description, Precompiled Headers are compiled, cached, and then automatically included into every file being compiled. So if there is some class that is needed everywhere or almost everywhere in a project, you can include that class inside the Prefix.pch file, which is created automatically in a new project, and it will be available everywhere. I really didn't like having to include the same class again and again in every View Controller when it was needed almost everywhere.

They also say that including files in Prefix.pch speeds up compilation later, once it and all files included in it have already been compiled once. But when you change the Precompiled Headers or the files included in them, compilation time goes up instead. So it's better to include code there that changes rarely.

It's also a good place to declare constants. That way they will also be available throughout the whole project. I don't like including a constants file everywhere either.

The automatically created AppName-Prefix.pch already contains so-called Preprocessor Macros. Here is an example of such a file:

#import <Availability.h>

#ifndef __IPHONE_3_0
#warning "This project uses features only available in iPhone SDK 3.0 and later."
#endif

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #import "YourEverywhereNeededClass.h"
#endif

#ifdef DEBUG
    #define DLog(...) NSLog(@"%s:%i %@", __PRETTY_FUNCTION__, __LINE__, [NSString stringWithFormat:__VA_ARGS__])
    #define DescLog(...) NSLog( @"%@", __VA_ARGS__ )
#endif

#define kNameOfConstant @"Constant Value"

Line 10 imports a file that is needed throughout the project.

Line 14 creates a custom function that prints the passed value, first showing which class, which method, and which line it was called from. For example, DLog( @"arm1.ru" ) will print:

-[SecondViewController viewWillAppear:]:84 arm1.ru

Class SecondViewController, method viewWillAppear, line 84, value "arm1.ru".

Line 15 is simply a convenient function: for example, to print values in an array to the console you normally had to write NSLog(@"%@", array) or NSLog( [array description] ). It's long and clumsy; much nicer when everything is short.

Line 18 defines a constant.

All in all, it's a very useful thing.

keyboard_return