3
votes

Let's say I have three custom objects in Objective-C: ClassA: UIViewController <ClassBDelegate> , ClassB: NSObject <ClassCDelegate>, ClassC: NSObject. ClassA is a subclass of UIViewController that will display an activity indicator until a certain network event happens in ClassC. ClassB has a ClassC, among other classes, and is responsible for relaying events from ClassC to ClassA. ClassA has a ClassB, and ClassB has a ClassC, there is no direct connection from ClassA to ClassC.

Now lets say once the particular network event happens in ClassC, that ClassC will fire off - (void)someAction;. ClassB conforms to the ClassC delegate protocol, and its - (void)classC:(ClassC *)classC didPerformSomeAction; method is called. In turn, ClassB fires off -(void)thisOtherAction;, and since ClassA conforms to the ClassB delegate protocol, its -(void)classB:(ClassB *)classB didPerformThisOtherAction; gets called, which effectively retrieves the network event from ClassC.

My question is, is this bad practice, and if so, is there an easier way to bridge the gap between ClassA and ClassC? I am hesitant to use a NSNotification because I think delegate protocols are more elegant. However, this seems sort of like a relay race to me. I would appreciate any information about popular conventions in a scenario such as this.

2
until you can follow your own code, that is okay – but local notifications are still here for you, if you'd like to avoid creating long chains. - holex

2 Answers

1
votes

Don't consider delegate more elegant than notifications, consider only that they apply to different situation:

Delegates - to be used when one item is interested in the result of or provides a service to one other item to which is has a relationship

Notifications - to be used when (potentially) multiple different items are interested in the occurrence of one (or more) events which are posted by other items to which they may or may not have a relationship

This isn't 100% hard and fast. You can create a delegate that can call back to many observers. You can also pass a block between classes to have some other object take responsibility for the delegate callback. But, your situation seems more appropriate to be handled by a notification.

1
votes

It seems that you are describing either mediator pattern or adapter pattern. It is also possible that you have a middle man code smell. It really depends on what you want to achieve.