Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forward declaration for objective-c interfaces

How do I forward declare this object:

@interface MyClass : NSObject <AVAudioSessionDelegate>
{

}

@end

in objective c

like image 957
aerlfredith Avatar asked May 28 '13 10:05

aerlfredith


People also ask

Is a forward declaration Objective C?

In Objective-C, classes and protocols can be forward-declared like this: @class MyClass; @protocol MyProtocol; In Objective-C, classes and protocols can be forward-declared if you only need to use them as part of an object pointer type, e.g. MyClass * or id<MyProtocol>.

What is forward declaration in C?

As others stated before, a forward declaration in C/C++ is the declaration of something with the actual definition unavailable. Its a declaration telling the compiler "there is a data type ABC".

What is a forward class Objective C?

Forward declarations are mainly to avoid circular imports, where one file imports another file which imports the first file etc. Basically when you import a file, contents of the file are substituted at the point of import when you build your project, which is then fed to the compiler.

Why should I use forward declarations?

A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. In the case of functions, this allows us to tell the compiler about the existence of a function before we define the function's body.


1 Answers

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.

like image 193
justin Avatar answered Sep 21 '22 15:09

justin