-1

bit of a n00b question this one but I haven't been able to find the answer on t'web, was just wondering what the rules are around whether to #import in the interface or the implementation ?

I just realised my (one) project is importing all over the place and I want to tidy it up. Is it sufficient to just import in the interface, will the implementation then pick this up?

Also, I did read via google that it's recommended to only #import classes that reside in a different framework , otherwise use @class. Can anyone verify that, is that best practice?

thanks in advance.

SM2011
  • 287
  • 3
  • 9

4 Answers4

2

Yeah, it is sufficient to import only in implementation file. If you have declared the class in .h file, then use forward declaration ie., @class ClassName; in .h file.

Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55
0

Well, definitely don't ever import .m files.

Also watch out with 2-way imports: don't let header1 import header2, while header2 imports header1. That's just going to go wrong.

The best approach would be to make a class diagram (UML or something) that shows which classes need which classes. You then know that you only need those imports.

Try to avoid importing files from headers - imports in implementation files are okay.

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
0

The best practice is to minimise the number of files that are imported so that a partial recompile does not have to import a file.

To do this note that @class X can be used whenever you do not access an instance or class variable of X or call a method of X. If you need the method or variable then you should #import. (Actually this distinction can only apply to the variables the program will compile and run if you call methods on classes declared with @class but you will get warnings of unknown n selectors which is not good practice)

With @class X declarations you can only reference the pointer to the class ie X *

This boils down to use @class in headers unless you are inheriting from the class. Use #import in the implementation files unless you are just passing a pointer through and not sending a message to anything of that class.

This is not 100% as there are precompiled headers so that a class that is used in most of your project can be #imported as that will be in the precompiled header and so only read once.

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
0

Caveat to all these rules, if you are importing a header that declares a protocol, be sure to put the import in the .h file.

Abizern
  • 146,289
  • 39
  • 203
  • 257