Search code examples
objective-cdelegatesprotocols

Good reasons to use delegates over class instances?


i have been asked a question about delegates, and i had some doubts about the right answer :

When you create your own protocol, what makes the difference between using a delegate, or just instantiating the class, and call a simple method?

I thought: with the delegate, you don't bother instantiate a new whole class, and you can set the delegate outside the class, and just call the method with the "delegate". Is it also a good thing to use delegates to avoid the unlimited imports? as when classA imports classB, and if you instantiate the class instead of using delegates, classB also imports classA, and it causes a crash?

Are there any other good reasons when you create your own protocol/delegate?


Solution

  • Well, look at an example.

    Assume you have "something" that happens to display a window as part of whatever it's doing. Without delegates or a similar setup, you'd have to be a subclass of "Window" to be able to handle window stuff, and you'd have to be a subclass of something else to handle whatever else you're doing. So it's either not possible, or you get into all sorts of multiple inheritance weirdness.

    Thus, you would probably end up making a subclass of whatever, and a sublcass of "Window", and instanciate objects for both, and have them communicate somehow. Which is exactly what a delegate does, except that you have to do it over and over again for all sorts of things. Like imagine a window with 10 buttons in it, each of which needs a button sublcass that doesn't really do all that much except for calling "ButtonXClicked" on your actual class. Again, see the "delegate" reimplemented here (yes, in Cocoa it's not a delegate; that would be the target/action. But it's not all that different from a delegate)?

    Thus, delegates are pretty much a convenience to connect objects that don't really have a "kind of" relationship as implied by deriving classes.

    It also allows you to connect objects that are "created elsewhere", like when you have something that creates an object and returns it to you: you can't really subsitute a subclass there, but the API might still allow you to do a "setDelegate:"-like thing to connect that object to your application.

    Sometimes delegates are more appropiate, sometimes subclasses are better, and there's probably cases where it doesn't really matter.