IOS enhanced knowledge (2) @ class
1. Why is @ class used?
Like C ++, OC also requires a header file (H file) and an implementation file (m file ). When you reference other classes, you need to introduce header files. Although it is okay to reference the header file, if you don't want to know the details of this class and want to know that it is only a class, the reference header file may be redundant and will increase the Compilation Time. With @ class, you can let the compiler know that it is a class without introducing any header file. For example:
@ Class B;
@ Interface A: NSObject
@ Property B * B;
@ End;
In extreme cases, if thousands of classes introduce the same header file and the class corresponding to the header file changes, the classes that introduce the header file must be re-compiled, @ class is not affected.
@ Class also solves an important problem, that is, dependency loops. That is, when two classes are referenced to each other, no matter which header file you reference first, the other class will be undefined. For example:
/// A. h
@ Interface A: NSObject
@ Property B * B; // introduce A. h B first. At this time, an error occurs during undefined compilation.
@ End;
/// B. h
@ Interface B: NSObject
-(Void) setFriend :( A *) a; // introduce B. h A first. At this time, the undefined compilation error occurs.
@ End;
We can easily solve this problem through @ class
/// A. h
@ Class B;
@ Interface A: NSObject
@ Property B * B; // Forward Declaration B compiled through
@ End;
/// B. h
# Import "A. h"
@ Interface B: NSObject
-(Void) setFriend :( A *) a; // introduce A. h A to be declared and compiled. Note: Class A can also be declared forward.
@ End;
2. Sometimes header files must be introduced
When you need to inherit, you must introduce the header file to understand its complete definition. The same is true when you implement an agreement. So we 'd better put the Protocol in a separate header file.
Of course, it is better not to introduce the header file. If you need to introduce some header files, you can also consider putting them into the category, the advantage is to increase compilation efficiency and reduce coupling between classes.
Today's highlights:
Unless necessary, the header file is not introduced. This reduces coupling and Compilation Time.
If you cannot forward the declaration, try to include the header file into the category.