Why use delegates at all? [closed]

我与影子孤独终老i 提交于 2019-12-20 07:17:41

问题


I have some questions about delegates in Objective-C:

  1. What's the point of using them at all? Why i can't just create class with all methods, that i need and then set object of this class as property (i.e. what's the convenience of using protocols)?
  2. Who invokes the methods of AppDelegate? Why there is a class for these methods, not a protocol?
  3. I read, that delegate methods contains words like "did", "will", "should", "become". So why the methods of ViewController named that way? How it is correlating with delegates?

回答1:


What's the point of using them at all? Why i can't just create class with all methods, that i need and then set object of this class as property (i.e. what's the convenience of using protocols)?

A single object can conform to multiple protocols, for example it could be both a UITableViewDelegate and a UIAlertViewDelegate. A single class cannot have multiple superclasses (even in languages where this is syntactically legal, we have long known that this creates significant problems, most famously the Diamond Problem).

Who invokes the methods of AppDelegate? Why there is a class for these methods, not a protocol?

The UIApplication invokes the methods. It is a protocol: UIApplicationDelegate. There just happens to be a class that conforms to that protocol.

I read, that delegate methods contains words like "did", "will", "should", "become". So why the methods of ViewController named that way? How it is correlating with delegates?

UIViewController is not a delegate, nor does it have a delegate (well, a transitioning delegate was added in iOS 7, but that doesn't change much). It is a class that is designed to be subclassed. These are methods that are intended to be overridden if you want to know when various events occur. That have similar names because they are called for similar reasons.




回答2:


A delegate is basically a listener for events that happen in another class. To highlight the usefulness of delegates, think about the AppDelegate file, which is a listener for high level system events, such as when the app terminates or when it enters the background. It allows you to specify a common policy for something that could happen "anywhere" in your program and "anytime" during execution. It gives you a greater sense of control.



来源:https://stackoverflow.com/questions/33768172/why-use-delegates-at-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!