vilhalmer
vilhalmer

Reputation: 1159

Stuck on a circular dependency with a one-to-many relationship

So I'm building a system in which there is a server object, and it generates Uploader objects. Both are defined as protocols/interfaces, whichever term you prefer. The Server object has a method which generates an Uploader and returns it, with the following signature:

- (id<Uploader>)generateUploader;

The Uploader needs to contain a reference back to the Server which created it, because it needs a reference to a Server to get the password from my keychain wrapper. So, it contains a method which returns its parent Server:

- (id<VayprServer>)parentServer;

Of course, this creates a circular dependency between the two protocols. Any ideas on how to fix this?

Thanks!
Billy

Upvotes: 0

Views: 243

Answers (2)

millenomi
millenomi

Reputation: 6589

To break the dependency, like all circular dependencies, you gotta forward-declare stuff in the .hs. In particular:

// VapyrServer.h

@protocol Uploader;

@interface Blah : …
…
- (id <Uploader>) generateUploader;
…

and

// VapyrServer.m

#import "Uploader.h"
…

and

// Uploader.h

@protocol VapyrServer;

@interface MoreBlah : …
…
- (id <VapyrServer>) parentServer;
…

and

// Uploader.m

#import "VapyrServer.h"
…

This way, the two .ms will see things declared in the correct order.

Upvotes: 1

BonyT
BonyT

Reputation: 10940

This is not necessarily an anti-pattern.

In a tree structure such as the Explorer Tree in Windows Explorer, the Tree exposes a collection of Nodes, but each Node has a reference to the Tree.

Upvotes: 0

Related Questions