Does Objective-C allow circular dependencies?

后端 未结 1 1656
天命终不由人
天命终不由人 2020-12-03 01:39

I\'m rewriting a Java library in Objective-C and I\'ve come across a strange situation. I\'ve got two classes that import each other. It\'s a circular dependency. Does Objec

相关标签:
1条回答
  • 2020-12-03 02:13

    Importing a class is not inheritance. Objective-C doesn't allow circular inheritance, but it does allow circular dependencies. What you would do is declare the classes in each other's headers with the @class directive, and have each class's implementation file import the other one's header. To wit:

    ClassA.h

    @class ClassB;
    
    @interface ClassA : NSObject {
        ClassB *foo;
    }
    @end
    

    ClassA.m

    #import "ClassB.h"
    
    @implementation ClassA
        // Whatever goes here
    @end
    

    ClassB.h

    @class ClassA;
    
    @interface ClassB : NSObject {
        ClassA *foo;
    }
    
    @end
    

    ClassB.m

    #import "ClassA.h"
    
    @implementation ClassB
        // Whatever goes here
    @end
    
    0 讨论(0)
提交回复
热议问题