C是否允许循环依赖

C是否允许循环依赖

本文介绍了Objective-C是否允许循环依赖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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不允许循环继承,但允许循环依赖.您要做的是使用@class指令在彼此的标头中声明这些类,并让每个类的实现文件导入另一个人的标头.发挥作用:

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:

@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

这篇关于Objective-C是否允许循环依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:08