Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Objective-C allow circular dependencies?

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?

like image 561
Moshe Avatar asked Mar 24 '11 21:03

Moshe


People also ask

Is it okay to have circular dependency?

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.

What is circular dependency in C?

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.

Does maven allow circular dependencies?

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.

Should I avoid circular dependency?

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.


1 Answers

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
like image 157
Chuck Avatar answered Oct 18 '22 14:10

Chuck