为什么要使用委托? [英] Why use delegates at all?

查看:160
本文介绍了为什么要使用委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Objective-C中的代表有一些疑问:

I have some questions about delegates in Objective-C:


  1. 完全使用它们有什么意义?为什么我不能只用所需的所有方法创建类,然后将此类的对象设置为属性(即使用协议的方便性)?

  2. 谁调用了以下方法AppDelegate?为什么对于这些​​方法有一个类,而不是协议?

  3. 我读到,委托方法包含诸如 did, will, should, become之类的词。那么为什么ViewController的方法采用这种方式呢?


推荐答案


重点是什么?完全使用它们?为什么我不能只用我需要的所有方法创建类,然后将此类的对象设置为属性(即使用协议的方便性)?

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)?

单个对象可以符合多种协议,例如它可以是 UITableViewDelegate UIAlertViewDelegate 。一个类不能有多个超类(即使在语法上合法的语言中,我们早就知道这会造成严重的问题,最著名的是钻石问题)。

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).


谁调用AppDelegate的方法?为什么对这些方法有一个类,而不是一个协议?

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

UIApplication 调用方法。它是一个协议: UIApplicationDelegate 。刚好有一个符合该协议的类。

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


我读到,委托方法包含诸如 did, will ,应该,成为。那么为什么ViewController的方法采用这种方式呢?

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 既不是委托,也不是委托它是否有一个委托(嗯,iOS 7中添加了一个过渡委托,但这并没有太大变化)。它是设计为子类化的类。如果您想知道何时发生各种事件,这些方法将被覆盖。它们之所以具有相似的名称,是因为它们因类似的原因被调用。

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.

这篇关于为什么要使用委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆