@class vs. #import

后端 未结 16 1055
渐次进展
渐次进展 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条回答
  •  渐次进展
    2020-11-21 23:35

    If you try to declare a variable, or a property in your header file, which you didn't import yet, your gonna get an error saying that the compiler doesn't know this class.

    Your first thought is probably #import it.
    This may cause problems in some cases.

    For example if you implement a bunch of C-methods in the header file, or structs, or something similar, because they shouldn't be imported multiple times.

    Therefore you can tell the compiler with @class:

    I know you don't know that class, but it exists. It's going to be imported or implemented elsewhere

    It basically tells the compiler to shut up and compile, even though it's not sure if this class is ever going to be implemented.

    You will usually use #import in the .m and @class in the .h files.

提交回复
热议问题