1

I know it is proper practice to put a forward class declaration (@class ClassA) in the .h and #import "ClassA.h" in the .m. And also I know doing that can make compiler compile it later on(until #import it in the .m).

Usually we use @class ClassA in A.h meanwhile add #import ClassA.h in A.m, though the compiler would not compile ClassA in A.h, still compiler have to compile it in the A.m. So why not use #import in A.h directly?

Mil0R3
  • 3,876
  • 4
  • 33
  • 61
  • http://stackoverflow.com/questions/9177265/why-use-forward-declaration-rather-than-import-in-h-file?rq=1 – ohho Nov 29 '12 at 04:09

2 Answers2

2

You almost never use @Class A in A.h. The common practice is to use @Class B in A.h and @Class A in B.h. The reason for this is to avoid circular dependencies in the .h files. If A.h imported B.h and B.h imported A.h, the compiler would explode from the circular dependency.

Your last sentence seems to be asking why we never import A.h in A.h. I think it's pretty obvious why that isn't done.

Remember, the header file (.h) is meant to tell the world the minimum possible about your declarations. It's there to tell the compiler - "Hey, we have a class (@interface) with some methods and properties. And those methods use these other classes. We use @class for those other classes because at this point in time we only need to know that there will be such classes eventually. It's just enough to make the compiler happy so it can do its job. Ultimately, the linker makes the final decision about whether those classes really exist somewhere.

The source file (.m) needs to do the actual importing because the compiler needs to verify that there really are the methods and properties you are trying to use. But the header file doesn't call methods and it doesn't call properties. It simply states - "This stuff exists".

rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

I use @class instead of #import in .h for two reasons:

  1. Makes circular dependencies possible.

  2. Reduces compile time.

I commonly find it useful to have mutual links, A->B and B->A, which is impossible without forward declarations.

Roger C S Wernersson
  • 6,362
  • 6
  • 34
  • 45