I wonder about Objective-C style.
I h开发者_开发百科ave FooClass.[hm] that depends on BarClass.[hm] for its implementation (though not for its interface). I can #import "BarClass.h"
either directly in FooClass.m or indirectly through FooClass.h. I wonder about the common choice for this.
You should ALWAYS #import
other classes in your .m
file.
If they happen to also be members of your class, you can forward declare them (by using the @class
directive) in your .h
file.
The reason for doing this is because when you #import
a .h
file, you only want to import declarations, not definitions. By using @class
and only #import
ing in .m
files, you are a) reducing overhead and b) makes for cleaner code.
Another reason you should do it this way was pointed out by Matt Gallagher:
The reasoning behind forward declarations in header files is that it avoids unnecessary dependencies. i.e. Imagine B.h forward declares A and B.m imports A.h. Then imagine C.m, D.m, E.m and F.m import B.h. After all this is done, A.h changes. Since A is only forward declared in B.h, only B.m needs to rebuild. Without forward declarations, C.m, D.m, E.m and F.m would all need to be rebuild if A changes
Example:
.h
file:
@class BarClass;
@interface FooClass : NSObject
...
@end
.m
file
#import "BarClass.h"
@implementation FooClass
...
@end
#import in .h or .m files
.h
file - publicinterface
of a class.m
file - privateimplementation
of the class
My rules are:
- Forward declaration[About] -
@class
inside.h
file - You should reduce of imports in
.h
- The accent should be on import in
.m
file that prevents dependency issues
When you need something in implementation
then you should import it in .m
. When you need something in interface
then you should import it in .h
.
[import angle brackets <>
and quote marks ""
]
精彩评论