I’ve no idea why, but on occasion I’ve managed to fix some compile errors, most notably
error expected specifier-qualifier-list before 'someClass'
by moving #import "someClass.h" from the .h file into the .m file. This has also worked with a couple of other problems i’ve encountered that have been (mysteriously from my point of view) related to headers.
Some cursory googling has turned up the answer “never import headers in header file” and that’s where the advice stops.
Either I’ve completely made this up, or I’ve picked up the habit from somewhere, but I thought the header was where headers were meant to be imported. Clearly not, but can anyone explain to me why that is, and what’s the preferred way of importing headers?
Unless you’re inheriting from the class that you’re including, you shouldn’t include headers in headers. If you need to include an object as an interface variable, you should use the
@classdirective instead; that’ll tell the compiler that the identifier refers to a class.Instead, import headers only in implementation files. The compiler will know that your instance variables are pointers to objects, but it doesn’t know the details of the object when parsing the header. All it needs to know is that it’s a class. The compiler can then see the methods of the class when parsing your implementation file; at that point, it does need the class, to verify that it responds to the messages you’re sending.
Update: I was going to update my answer to respond to some later questions, but Rob Napier has a good follow-up.