Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does cocoa use delegates rather than inheritance?

Why does cocoa use delegates rather than inheritance?

like image 398
Casebash Avatar asked Jan 14 '10 22:01

Casebash


2 Answers

With delegates, you can have one object be the delegate of many other objects. For example, you can have your MyController instance be the delegate of an NSTableView, an NSTextField, an NSWindow, and any other objects that compose your interface. This gives a compact place to put all of your user interface code related to one section of your UI.

If you'd done that with subclassing, you'd have to create one subclass every object you wanted callbacks from.

Also, this is a classic inheritance vs composition question

like image 129
Jon Hess Avatar answered Sep 21 '22 22:09

Jon Hess


In general creating a subclass can be a time consuming process, requiring a lot of groundwork, and overriding various template methods.

Meanwhile, using a delegate allows you to create a simple object that answers a few specific question or reacts in various ways.

Now when you combine this with the dynamism that you can achieve by swapping out delegates on the fly it can create a very flexible robust system that promotes more code reuse.

There is some general discussions regarding these things here and here. You can also find some older SO questions here and here.

like image 30
Bryan McLemore Avatar answered Sep 20 '22 22:09

Bryan McLemore