Objective-C: Forward Class Declaration

Old McStopher picture Old McStopher · Mar 4, 2011 · Viewed 45.6k times · Source

I'm writing a multiview app that utilizes a class called RootViewController to switch between views.

In my MyAppDelegate header, I create an instance of the RootViewController called rootViewController. I've seen examples of such where the @class directive is used as a "forward class declaration," but I'm not quite sure what this means or accomplishes.

#import <UIKit/UIKit.h>
@class RootViewController;
@interface MyAppDelegate
.
.
.

Answer

Mac picture Mac · Mar 4, 2011

It basically tells the compiler that the class RootViewController exists, without specifying what exactly it looks like (ie: its methods, properties, etc). You can use this to write code that includes RootViewController member variables without having to include the full class declaration.

This is particularly useful in resolving circular dependencies - for example, where say ClassA has a member of type ClassB*, and ClassB has a member of type ClassA*. You need to have ClassB declared before you can use it in ClassA, but you also need ClassA declared before you can use it in ClassB. Forward declarations allow you to overcome this by saying to ClassA that ClassB exists, without having to actually specify ClassB's complete specification.

Another reason you tend to find lots of forward declarations is some people adopt a convention of forward declaring classes unless they absolutely must include the full declaration. I don't entirely recall, but possibly that's something that Apple recommends in it's Objective-C guiding style guidlines.

Continuing my above example, if your declarations of ClassA and ClassB are in the files ClassA.h and ClassB.h respectively, you'd need to #import whichever one to use its declaration in the other class. Using forward declaration means you don't need the #import, which makes the code prettier (particularly once you start collecting quite a few classes, each of which would need an `#import where it's used), and increases compiling performance by minimising the amount of code the compiler needs to consider while compiling any given file.

As an aside, although the question is concerned solely with forward declarations in Objective-C, all the proceeding comments also apply equally to coding in C and C++ (and probably many other languages), which also support forward declaration and typically use it for the same purposes.