I'm writing a multiview app that utilizes a class called
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 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
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
ClassB are in the files
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.