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?
Asked
Active
Viewed 7,593 times
19
-
I've re-worded the title and re-tagged the question. – dty Mar 24 '11 at 21:18
1 Answers
56
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

Chuck
- 234,037
- 30
- 302
- 389
-
I'm trying to implement circular dependency https://stackoverflow.com/questions/44290130/ios-circular-dependency-to-call-method-in-each-other-class but for some reason is not working. Can you please take a look – user2924482 May 15 '19 at 18:32