-->

Why use delegates at all? [closed]

2020-05-08 08:34发布

问题:

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.