Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why and where to use a delegate in objective c

I’m a new iPhone programmer

I have created some small views without delegates.... If a program can run without a delegate, then why use them. What is need for them, I have seen some programs on net having delegates.

I’m confused, please answer.

like image 638
Ranjeet Sajwan Avatar asked Jul 24 '10 08:07

Ranjeet Sajwan


1 Answers

Delegates are a pattern that allows some object to notify another object when stuff happens. Lots of delegate methods start with "will" or "did" which get called before and after an event occurs, respectively.

Let's say you have a UITableView, and you want to know when the user taps a cell so that you can process their choice. You assign a delegate to the table view that implements the delegate method tableView:didSelectRowAtIndexPath:.

The nice things about this approach is that the table view doesn't have to know or care about what this other delegate object is or how it works. It allows the object generating the events to stay focused and clean, only dealing with it's own state. When it does something noteworthy, it will send a message to it's delegate. And the delegate object doesn't need to know anything about the internal state of the other object at all. It only needs to know that it did something important.

And this fits the Model/View/Controller (MVC) approach of the iPhone SDK well. The View should only be concerned about how it displays itself, and the controller is a delegate of the view for when things change.

Programming with delegates is not a required language feature Objective-C. It's merely a design pattern the SDK uses quite a bit. But it's a fairly good pattern that can help keep your code cleaner.

like image 141
Alex Wayne Avatar answered Nov 11 '22 01:11

Alex Wayne