Is it always inappropriate to use #import as more than an absolute necessity for Objective-C interfaces?

I am well aware that the general rule is that you should import only the necessary base class interfaces, protocol interfaces, etc. - to compile and use the @class class for everything, declared. However, I came across the following scenario, in which it seemed to me that #import was a more suitable 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 

First, I just scroll forward ClassA and ClassB (since the components of classCObjects have ClassC only by contract). That was my initial instinct.

But after trying to use ClassD elsewhere, I quickly realized that I also had to import ClassA , ClassB and ClassC along with ClassD wherever I used it. When using ClassD doesn't seem to need to worry about another class. I thought that basically the user of ClassD should really only care about importing ClassD.h and assume that he can work with the whole class without many other #import statements. Given the above approach, I have included in my interface everything I need to work in the ClassD domain.

Is there a good reason why this approach is not perfect, except that "you included more than is absolutely necessary for compilation?"

+7
source share
2 answers

While the strategy that you usually follow β€” don’t import more than you need β€” is a terrific, stylish style and a great thing to strive for in general, don’t sweat too much in difficult cases. Just #import what you need.

In practice, on a modern machine, the only effect beyond #import will be to add a few unobservable microseconds to your compilation time. Use the developer time you save to build your application. :)

+10
source

As a programmer, you need to continue declaring classes where possible. This significantly reduces the compilation time of large projects. But spending too much time on where to forward the ad will in no way help you create a very attractive app. So, if you can forward the ad, do it, but it’s not necessary.

+1
source

All Articles