forward declaration for objective-c interfaces

aerlfredith picture aerlfredith · May 28, 2013 · Viewed 11.3k times · Source

How do I forward declare this object:

@interface MyClass : NSObject <AVAudioSessionDelegate>
{

}

@end

in objective c

Answer

justin picture justin · May 28, 2013

This is a forward declaration of an ObjC type:

@class MyClass;

And this is a forward declaration of an ObjC protocol:

@protocol AVAudioSessionDelegate;

For those of you who are curious why this is useful: Forward declarations can be used to significantly reduce your dependencies and significantly reduce your build times because it allows you to avoid #importing headers and/or entire frameworks (which then #import other frameworks). When forward declarations are not used, many unnecessary headers are visible to other parts of your program -- changing one header can cause many files to be recompiled, and the compilation and link times will go up. Because ObjC types are always dealt with as pointers (at our abstraction level), the forward declaration is sufficient in most cases. You can then declare your ivars in your @implementation or class continuation and the #import can then go in the *.m file. Another reason is to avoid circular dependencies.