Imports and includes in header files - when is it okay?

115 views Asked by At

I've read that the rule is to not #import or #include anything in .h files. Is that really true, though?

Just today I've run into two separate occasions where I had to do it, one where I import a header file that contains a typedef enum because my method stubs use it as parameters and another where I have to import a header file to declare delegatation.

What's the actual rule for these types of situations? Is it sometimes okay to do so – and if not, how can I do it differently?

3

There are 3 answers

0
i_am_jorf On BEST ANSWER

There's no hard rule, but sometimes you do have to do it. You will also need to do if you inherit from something or need the protocol declaration.

In general I would restate the rule as "use forward declarations of @class and @protocol whenever possible."

0
Aleks N. On

If you've read such a rule, that rule is wrong. You can include (and import, which is just a safer way of include) things into your header, if that's something required for the interface declaration. Otherwise save it for the implementation files.

0
johnpatrickmorgan On

If ClassA depends on ClassB such that a consumer of ClassA is certainly going to need to import ClassB in order to make use of ClassA, I would prefer header imports over forward declarations.