How do I forward declare this object:
@interface MyClass : NSObject <AVAudioSessionDelegate>
{
}
@end
in 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>.
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".
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.
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.
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 #import
ing 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With