I'm well aware that the general rule of thumb is you should only import what is necessary—base class interfaces, protocol interfaces, etc.—for a class to compile and use @class
for everything that can be forward-declared. However, I ran into the following scenario in which I felt like #import
was a more appropriate solution:
#import "ClassA.h" // Previously, @class ClassA;
#import "ClassB.h" // Previously, @class ClassB;
#import "ClassC.h" // Unnecessary to forward-declare
@interface ClassD : NSObject
@property (nonatomic, retain) ClassA * classAObject;
@property (nonatomic, retain) ClassB * classBObject;
@property (nonatomic, copy) NSArray * classCObjects;
@end
At first, I simply forward-declared ClassA
and ClassB
(as the components of classCObjects
are of ClassC
only by contract). This was my initial instinct.
But after trying to use ClassD
elsewhere, I quickly realized that I had to also import ClassA
, ClassB
, and ClassC
along with ClassD
everywhere I used it. This seems like something another class shouldn't have to care about when using ClassD
. My thinking was that, basically, a user of ClassD
should really only care about importing ClassD.h
and assume it can work with the entire class without a bunch of other #import
statements. Given the above approach, I've basically included everything necessary to work within the domain of ClassD
right in its interface.
Is there a strong reason why this approach is not ideal, except for "you've included more than is absolutely necessary for compilation?"
While the strategy you're generally following-- don't import more than necessary--is awesome, classy style and a great thing to aim for in general, don't sweat the tricky cases too much. Just #import
what you need.
In practice, on a modern machine, the only effect over-#import
ing will have is to add a few unobservable microseconds to your compile time. Use the developer time you'll save for making your app awesomer. :)
As a programmer, one should go forward declaration of classes where ever it is possible. It considerably reduces compilation time on big projects. But spending too much time on where to forward declare isn't any way going to help you design a very good attractive app. So, if you can forward declare do it but it is not a must.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With