开发者

why and where to use a delegate in objective c

开发者 https://www.devze.com 2023-01-08 21:55 出处:网络
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

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 开发者_如何学Pythonanswer.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消