@class vs. #import

后端 未结 16 1326
渐次进展
渐次进展 2020-11-21 22:42

It is to my understanding that one should use a forward-class declaration in the event ClassA needs to include a ClassB header, and ClassB needs to include a ClassA header t

16条回答
  •  萌比男神i
    2020-11-21 23:31

    If you see this warning:

    warning: receiver 'MyCoolClass' is a forward class and corresponding @interface may not exist

    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".

提交回复
热议问题