Objective-C: Forward Class Declaration Objective-C: Forward Class Declaration objective-c objective-c

Objective-C: Forward Class Declaration


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.


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. If you have circular imports, you'd have an infinite loop which would never compile. Fortunately xcode will tell you about this before trying. The forward declaration says "Don't import this class but just know that it exists. " Without either an import or a forward declaration, you get an error that no such class exists.


@class or forward class declaration(incomplete type) - just tell to a compiler that this class exists. In this case the compiler does not know anything about type memory layout - class size, members, or methods. That is why you can only use for defining classes via references and pointers.

Advantages:

  • reduce build time
  • break cyclic references