(一)英文对话部分原文
问题: When does one use #import
and when does one use @class
?
解释:you need to #import
the file, but you can do that in your implementation file (.m), and use the @class
declaration in your header file.
@class
does not (usually) remove the need to #import
files, it just moves the requirement down closer to where the information is useful.
For Example
If you say @class myCoolClass
, the compiler knows that it may see something like:
myCoolClass *myObject;
It doesn't have to worry about anything other than myCoolClass
is a valid class, and it should reserve room for a pointer to it (really, just a pointer). Thus, in your header, @class
suffices 90% of the time.
However, if you ever need to create or access myObject
's members, you'll need to let the compiler know what those methods are. At this point (presumably in your implementation file), you'll need to #import "myCoolClass.h"
, to tell the compiler additional information beyond just "this is a class".
(二)@class VS #import
@class
doesn't import the file, it just says to the compiler "This class exists even though you don't know about it, don't warn me if I use it". #import
actually imports the file so you can use all the methods and instance variables. @class
is used to save time compiling (importing the whole file makes the compile take more time). You can use #import
if you want, it will just take longer for your project to build.