ios - 为什么要使用委托(delegate)?

标签 ios objective-c xcode delegates

<分区>

我对 Objective-C 中的委托(delegate)有一些疑问:

  1. 使用它们有什么意义?为什么我不能用我需要的所有方法创建类,然后将此类的对象设置为属性(即使用协议(protocol)有什么便利)?
  2. 谁调用 AppDelegate 的方法?为什么这些方法有一个类,而不是一个协议(protocol)?
  3. 我读到,委托(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),例如它可以同时是 UITableViewDelegateUIAlertViewDelegate。一个类不能有多个父类(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),但变化不大)。它是一个旨在被子类化的类。如果您想知道各种事件何时发生,这些方法将被覆盖。它们具有相似的名称,因为它们出于相似的原因被调用。

关于ios - 为什么要使用委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56732497/

相关文章:

ios - 无法使用 WatchConnectivity (swift) 发送自定义对象

iOS 越狱控制台应用程序,权利

objective-c - 在 OS X 上实现后台应用程序的最佳方式

ios - 将我现有的应用程序发布到 App Store 时出错

ios - 如何将 iOS 应用程序从一个开发者帐户转移到另一个开发者帐户?

objective-c - 如何在 Cocoa 中制作一个未装饰的窗口?

iphone - 原生 iOS 应用程序是否可以与 Safari 浏览器交互?

ios - XML 解析器仅加载第一个对象

xcode - 当在 Swift Spritekit 中触摸并按住屏幕时,我将如何向上移动我的节点?

ios - CGIImage 在 segue 之后为 nil