Objective-C允许循环依赖吗?

时间:2022-10-04 11:58:48

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 Objective-C support such a situation? If not, how do you recommend I rewrite it?

我正在用Objective-C重写一个Java库,我遇到了一个奇怪的情况。我有两个相互导入的类。这是一个循环依赖。Objective-C是否支持这种情况?如果没有,你如何推荐我重写?

1 个解决方案

#1


53  

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:

导入类不是继承。Objective-C不允许循环继承,但允许循环依赖。您要做的是使用@class指令在彼此的头文件中声明类,并让每个类的实现文件导入另一个类的头文件。即:

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

#1


53  

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:

导入类不是继承。Objective-C不允许循环继承,但允许循环依赖。您要做的是使用@class指令在彼此的头文件中声明类,并让每个类的实现文件导入另一个类的头文件。即:

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