Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone please explain delegates in objective-c?

I have been using Objective-C for a while and pretty much understand most of its features. However, the concept of delegates eludes me. Can someone please give a succinct and easy to comprehend explanation of what delegates are, how they are used in the iPhone SDK, and how I can best make use of them in my own code?

Thank you!

like image 828
Jason Avatar asked Nov 30 '25 17:11

Jason


1 Answers

There are a couple main reasons to use delegates in Objective-C, which are subtly different:

  1. Enhancing the base functionality of a framework class. For example, a UITableView is pretty boring on its own, so you can give it a delegate to handle the interesting bits (creating table cells, adding text to section headers, what have you). This way, UITableView never changes, but different table views can look and act very differently.

  2. Communicating to parent objects in your dependency hierarchy. For example, you may have a view with a button that the user may push to do something that affects other views. The view will have to send a message to its parent view, or perhaps the view controller, so that it can create or destroy or modify other views. To do this you'd pass the parent object into your view, most likely through a protocol, as a weak reference (in Objective-C, an assign property). The view could then send any message declared in the protocol to the parent, or delegate, object.

This approach need not involve views. For example NSURLConnection passes event back to its delegate, which may be the object that created it, using this mechanism.

like image 105
Adam Milligan Avatar answered Dec 03 '25 08:12

Adam Milligan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!