Monday, July 6, 2009

Objective-C: When should you use @class instead of #import

Say you're looking at AppController.h, which contains this code:

#import
@class PreferenceController;

@interface AppController : NSObject
{

PreferenceController *preferenceController;
}

-(IBAction)showPreferencePanel:(id)sender;

If you are wondering why @class is used within AppController.h, Aaron Hillegass in "Cocoa(R) Programming for Mac(R) OS X (3rd Edition)" explains:

The "@class PreferenceController;" line tells the compiler that there is a class PreferenceController. You can then make the following declaration without importing the header file for PreferenceController:

PreferenceController *preferenceController;

You could replace

@class PreferenceController;

with

#import "PreferenceController.h"

The #import statement would import the header, and the compiler would learn PreferenceController was a class. Because the import command requires the compiler to parse more files, @class will often result in faster builds.

No comments:

Post a Comment