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?
and, yes, cyclic dependencies are bad: They cause programs to include unnecessary functionality because things are dragged in which aren't needed. They make it a lot harder to test software. They make it a lot harder to reason about software.
In software engineering, a circular dependency is a relation between two or more modules which either directly or indirectly depend on each other to function properly. Such modules are also known as mutually recursive.
Maven does not allow cyclic dependencies between projects, because otherwise, it is not clear which project to build first. So you need to get rid of this cycle.
Ideally, circular dependencies should be avoided, but in cases where that's not possible, Nest provides a way to work around them. A forward reference allows Nest to reference classes that have not yet been defined by using the forwardRef() utility function.
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
#import "ClassB.h"
@implementation ClassA
// Whatever goes here
@end
@class ClassA;
@interface ClassB : NSObject {
ClassA *foo;
}
@end
#import "ClassA.h"
@implementation ClassB
// Whatever goes here
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With