Jul 27

Objective-C supports two directives: Compiler and Preprocessor. Compiler directives are prepended by ‘@’ while preprocessor ‘#’. I’ve been exposed to ‘#’ for awhile with C/C++, with ‘@’ being new with Objective-C. One interesting Compiler Directive is @class. This is actually similar to the #import, but with one big advantage.

Imagine that there is a class Shape that contains a position defined by a Location object. Shape never does anything with this Location except provide accessors, it never calls any of Location’s methods, etc. You can express this as below:

#import "Location.h"

@interface Shape : NSObject {
 Location *center;
}

@property *Location center;

However, because we are never actually “using” the Location object, we can be more efficient:

@class Location;
@interface Shape : NSObject {
 Location *center;
}

@property *Location center;

This tells the Compiler that we don’t need to know about its definition (and thus, don’t need to process the entire .h file) as we are not using it. @class gives the Compiler just enough information to compile, and allow “Shape” to contain the object.

Tagged with:
preload preload preload