@class vs. #import

后端 未结 16 1044
渐次进展
渐次进展 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:34

    Three simple rules:

    • Only #import the super class, and adopted protocols, in header files (.h files).
    • #import all classes, and protocols, you send messages to in implementation (.m files).
    • Forward declarations for everything else.

    If you do forward declaration in the implementation files, then you probably do something wrong.

    0 讨论(0)
  • 2020-11-21 23:34

    if we do this

    @interface Class_B : Class_A
    

    mean we are inheriting the Class_A into Class_B, in Class_B we can access all the variables of class_A.

    if we are doing this

    #import ....
    @class Class_A
    @interface Class_B
    

    here we saying that we are using the Class_A in our program, but if we want to use the Class_A variables in Class_B we have to #import Class_A in .m file(make a object and use it's function and variables).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-21 23:38

    Forward declaration just to the prevent compiler from showing error.

    the compiler will know that there is class with the name you've used in your header file to declare.

    0 讨论(0)
提交回复
热议问题