spring
spring

Reputation: 18487

why use forward declaration rather than #import in .h file?

I'm a beginner iOS/ObjectiveC coder and am trying to understand some details rather than just dumbly following the example code I see.

I think I get the gist of a forward declaration in a .h file: it tells the compiler that the specified class is a "player to be defined later" - and then the header is imported in the .m file.

What I don't understand is why not just import the class header in the header where the class is referenced, rather than use a forward declaration? My understanding of #import is it won't import the header more than once (as would #include - which necessitates the if_def stuff).

Do I have this all wrong?

Upvotes: 1

Views: 1519

Answers (4)

Jon Steinmetz
Jon Steinmetz

Reputation: 4124

One reason to use forward references is compiler speed. A header may be included in many other files and those files may not need the definitions included in your header file. Since included files are included by the preprocessor, having a lot of includes or large included files can greatly increase the lines of code that the compiler has to deal with.

You can see this yourself by using the preprocess command in Xcode to see the output of the preprocessor. By forward declaring classes in the header you are removing all of the code that would have been included by the header file.

Upvotes: 4

VsSoft
VsSoft

Reputation: 288

There's a good writeup on the historical issues driving forward declaration in C and it's subsets at Why are forward declarations necessary?

Long story short - this used to be more of an issue when memory was limited. Nowadays it's less crucial but can help speed compilation up in a large project.

Upvotes: 0

justin
justin

Reputation: 104698

It's used to minimize dependencies. When your projects grow large, your imports for each file to compile would grow into a huge mess of dependencies because everything depended on everything. This makes the process of compilation much slower because it must read and parse tons of information unnecessarily.

Upvotes: 0

barley
barley

Reputation: 4463

My use case is where there is cyclic reference. For example, AppDelegate has an ivar of a ViewController instance, and for some reason the ViewController wants to have reference to AppDelegate too (in .h). In this case, I would use #import in AppDelegate only, and forward declaration in ViewController. Otherwise, it will not compile.

Upvotes: 1

Related Questions