In objective-C, when a class needs to reference another class, that is, to establish a composite relationship, you need to create a pointer to the referenced class in the Class header file. For example:
Car. h
#import @interface Car:NSObject{ Tire *tires[4]; Engine *engine;}...
The implementation class is omitted first. If you compile it like this, the compiler will report an error, telling you that it does not know what tire and engine are.
At this time, there are two options: one is the import header file of the two referenced classes, and the other is to declare tire and engine as class names using @ class. The difference between the two is:
- Import will contain all information about this class, including entity variables and methods, while @ class only tells the compiler that the name declared after it is the name of the class. As for how these classes are defined, don't worry about it for the moment. I will tell you later.
- In header files, you only need to know the name of the referenced class. You do not need to know its internal entity variables and methods. Therefore, in header files, @ class is generally used to declare this name as the class name. In the implementation class, because the internal object variables and methods of the referenced class are used, # import must be used to include the header file of the referenced class.
- In terms of compilation efficiency, if you have 100 header files # imported the same header file, or these files are referenced in sequence, such as a-> B, B-> C, c-> D. When the header file at the beginning changes, all the classes that reference it later need to be re-compiled. If there are many classes, this will take a lot of time. Instead, @ class is not used.
- If there is a circular dependency such as a-> B, B-> A, if # import is used to contain each other, a compilation error occurs, if @ class is used to declare each other in the header files of the two classes, no compilation error occurs.
Therefore, in general, @ class is placed in the interface, just to reference this class in the interface and use this class as a type. In the implementation class that implements this interface, if you need to reference the object variables or methods of this class, you still need to import the classes declared in @ class.
For example:
A.h
@classRectangle;@interfaceA:NSObject{...}
A.M
#import Rectangle@implementationA...
Article transferred from: http://blog.prosight.me/index.php/2009/09/347