1. Why Use @class
like the C + + language, OC also needs a header file (h file), an implementation file (M file) . When you refer to other classes, you need to introduce a header file. Although there is no problem referencing the header file, if you do not want to know the details of this class, just want to know that it is just a class, referencing the header file may seem redundant and will increase the compile time. With @class, you can let the compiler know that it is a class without introducing any header files. For example:
@class B;
@interface A:nsobject
@property b* B;
@end;
In extreme cases, if there are thousands of classes that introduce the same header file, the class that introduces the header file needs to be recompiled when the class that corresponds to the header file changes and changes, and @class is not affected by this.
@class can also solve an important problem, which is to rely on circular relationships. That is, when two classes refer to each other, the other class is undefined, regardless of which header file you refer to first. Like what:
A.h
@interface A:nsobject
@property b* B; Introduction of A.h B is not defined at this time there is an error in compiling
@end;
B.h
@interface B:nsobject
-(void) Setfriend: (A *) A; Introduce B.h A at this time there is no compilation error defined
@end;
We easily solve this problem by @class
A.h
@class B;
@interface A:nsobject
@property b* B; Forward declaration B compiled by
@end;
B.h
#import "A.h"
@interface B:nsobject
-(void) Setfriend: (A *) A; Introduced A.h A is declared, compiled by note: A class can also make a forward declaration
@end;
2, sometimes must introduce the header file
When you need to inherit, you must introduce the header file and know its full definition. When you implement an agreement, the same is true. So we'd better put the protocol in a single header file.
Of course, it is best not to introduce a header file, if you need to introduce some header files, you can also consider the classification (category), the benefit is to increase the efficiency of the compilation and reduce the coupling between classes.
Today's Highlights:
The header file is not introduced unless it is necessary. Doing so reduces the coupling and reduces compilation time.
When you cannot forward the declaration, try to put the introduction of the header file into the category.
iOS Hardening Knowledge (2) Application of @class