Objective-C: @class Directive before @interface?

前端 未结 4 1704
星月不相逢
星月不相逢 2020-11-28 20:08

What is the difference between these two class declarations? I don\'t understand why @class is utilized here. Thanks.

@class TestClass;

@interface TestCl         


        
4条回答
  •  遥遥无期
    2020-11-28 21:06

    @class exists to break circular dependencies. Say you have classes A and B.

    @interface A:NSObject
    - (B*)calculateMyBNess;
    @end
    
    @interface B:NSObject
    - (A*)calculateMyANess;
    @end
    

    Chicken; meet Egg. This can never compile because A's interface depends on B being defined and vice-versa.

    Thus, it can be fixed by using @class:

    @class B;
    @interface A:NSObject
    - (B*)calculateMyBNess;
    @end
    
    @interface B:NSObject
    - (A*)calculateMyANess;
    @end
    

    @class effectively tells the compiler that such a class exists somewhere and, thus, pointers declared to point to instances of said class are perfectly valid. However, you couldn't call a method on an instance reference whose type is only defined as an @class because there is no additional metadata available to the compiler (I can't remember if it reverts the call site to being evaluated as a call through id or not).

    In your example, the @class is harmless, but entirely unnecessary.

提交回复
热议问题