Questions about import and @class usage
one.@classThe emergence of the product can appropriately reduce the compilation time and improve efficiency.
Now suppose there are two classes, one is the Teacher class and the other is the Students class.
Teacher Class
#import <Foundation/> #import "" @interface Teacher : NSObject @property (copy,nonatomic)NSString *firstName; @property (copy,nonatomic)NSString *lastName; @property (strong,nonatomic)Students *student; @end
Three properties are declared in the class, one of which is the Students class attribute. At this time, since you are using the Students class, you need to import the header file of this class. As above code.
Note: The import is imported at this time. This method is feasible but not elegant enough. There is a problem. In the declaration file, we do not need to know all the details of the Students class, we only need to know that the class name is Students. Use @class to solve the problem as follows, which is called "forward declaration" this class.
#import <Foundation/> @class Students; @interface Teacher : NSObject @property (copy,nonatomic)NSString *firstName; @property (copy,nonatomic)NSString *lastName; @property (strong,nonatomic)Students *student; @end
#import "" #import "" @implementation Teacher @end
The implementation file of the Teacher class needs to know all the excuse details of the Students class, so you need to use import "" at this time.
Try to delay the timing of introducing header files and only introduce them when necessary, so as to reduce the number of header files required by users of the class. If you import it with import when you are in the .h file, you will introduce a lot of unnecessary content, which will inevitably increase the compilation time.
two.@classThe emergence of two categories also refers to each other.
#import <Foundation/> #import "" @interface Teacher : NSObject @property (copy,nonatomic)NSString *firstName; @property (copy,nonatomic)NSString *lastName; @property (strong,nonatomic)Students *student; @end
#import <Foundation/> #import "" @interface Students : NSObject @property (strong,nonatomic)Teacher *teacher; @end
Import "" in the Students class, and import "Students" in the Teacher class, which causes circular reference problems, and endless compilation occurs when the program is compiled. At this time, you only need to change one of the imports to @class. If the .h file of both needs to know all the excuse details of the other class, the best solution is to use @class all.
summary
Do not introduce header files unless it is indeed necessary. Generally speaking, a forward declaration should be used in a .h file to mention other classes, and then the header files of those classes should be introduced in the .m file. Doing so minimizes the coupling of the class.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.