我对 Objective-C 中的委托(delegate)有一些疑问:
- 使用它们有什么意义?为什么我不能用我需要的所有方法创建类,然后将此类的对象设置为属性(即使用协议(protocol)有什么便利)?
- 谁调用 AppDelegate 的方法?为什么这些方法有一个类,而不是一个协议(protocol)?
- 我读到,委托(delegate)方法包含诸如“做过”、“将”、“应该”、“成为”之类的词。那么为什么 ViewController 的方法会这样命名呢?它与委托(delegate)的关系如何?
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)?
单个对象可以符合多个协议(protocol),例如它可以同时是 UITableViewDelegate
和 UIAlertViewDelegate
。一个类不能有多个父类(super class)(即使在语法上合法的语言中,我们早就知道这会产生重大问题,最著名的是 Diamond Problem)。
Who invokes the methods of AppDelegate? Why there is a class for these methods, not a protocol?
UIApplication
调用方法。它是一个协议(protocol):UIApplicationDelegate
。恰好有一个类符合该协议(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
不是委托(delegate),也没有委托(delegate)(好吧,iOS 7 中添加了过渡委托(delegate),但变化不大)。它是一个旨在被子类化的类。如果您想知道各种事件何时发生,这些方法将被覆盖。它们具有相似的名称,因为它们出于相似的原因被调用。