Reputation: 3192
This has a sort of Responder Chain feel to it, but the difference there is, the responder chain is a defined operation on views and view controllers specifically.
Well, I need to pass along a method call through several unrelated classes, and being fairly new to Objective-C, i'm not sure if it would be a hack to define a protocol, and then implement that protocol on every class that the call needs to pass through.
For example...
ClassA is the delegate to ClassB.
ClassB is the delegate to ClassC
... hence the 'responder chain' feel.
Does this make sense for the code to pass along a call from C to B to A.
I assume at some point, when the chain gets too long, you'd probably recommend a notification technique instead, but I don't know what that recommended length might be.
@protocol DidSomething
-(void)userDidSomething:(NSString*)something
@end
ClassA <DidSomething>
-(void)userDidSomething:(NSString*)something
{
NSLog(@"The user did something %@",something);
}
ClassB <DidSomething>
-(void)userDidSomething:(NSString*)something
{
[self.delegate userDidSomething:something];
}
ClassC <DidSomething>
-(void)thatWasInteresting
{
[self.delegate userDidSomething:@"Cool"];
}
Upvotes: 2
Views: 121
Reputation: 22701
Another alternative is using NSNotificationCenter
to post NSNotification
s. Object can add themselves as observers. Depending on your needs, this might be a good alternative to passing a message through a chain of delegate.
It is especially useful if more than one object needs to respond to a message.
Upvotes: 2
Reputation: 162712
Nope. Nothing wrong with that. Save for the potential complexity.
You could define it as a protocol, if you want. Or you could define it as a common abstract superclass (if possible).
Protocols are generally the way to go these days and using @optional
requires the use of a respondsToSelector:
test (or conformsToProtocol:
).
All in all, though, you should be very careful about the use of such a pattern. Specifically, it implies a lot about the architecture of your application and, thus, you want to make sure the architecture is sound.
Upvotes: 3