对Objective-C中的委托有点困惑 [英] Little confused on Delegates in Objective-C

查看:30
本文介绍了对Objective-C中的委托有点困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Objective-C 有一定了解,并且正在编写一本 iPhone SDK 书籍(来自一本刚刚编写控制台程序的 Obj-C 书籍).它试图向代表解释,尽管它很匆忙,并且并不真正理解它试图传达的内容.我对它们是什么以及何时使用它们感到有些困惑.

I know a good bit of Objective-C and I'm working on a iPhone SDK book (coming from a Obj-C book that just did console programs). It attempted to explain delegates though it was rushed and didn't really understand what it was trying to convey. I'm a little confused on what they are and when you would use them.

基本上它是说它们是代表另一个对象负责做某些事情的类.

Basically it said they are classes that take responsibility for doing certain things on behalf of another object.

有人愿意详细说明吗?

谢谢!

推荐答案

将委托视为依赖关系方向的反转.在大多数框架中,客户端会将所需的依赖项注入到实例中,通常是在构造函数中或通过 setter.

Think of delegates as inversion the direction of dependencies. In most frameworks the clients will inject the required dependencies into instances, usually in the constructor or by setters.

可可则相反;而是在需要时请求数据.

Cocoa does the reverse; instances instead request the data when and if it is needed.

委托方法主要有四种类型:

There are four main types of delegate methods:

  • 有条件地在之前 - 表示某事即将发生,但委托可能会中止.名称中始终包含应该"一词.
    示例:searchBar应该EndEditing:.
  • 无条件之前 - 表示某事即将发生.名称中始终包含 will 这个词.
    示例:applicationWillTerminate:.
  • 无条件之后 - 表示发生了什么事.名称中始终包含 did 这个词.
    示例:applicationDidFinishLaunching:.
  • 定制器 - 请求有关如何运作的信息.名称包括所需的信息.
    示例 tableView:viewForHeaderInSection:.
  • Conditionally before - Signals something is about to happen, but the delegate may abort. Name always include the word Should.
    Example: searchBarShouldEndEditing:.
  • Unconditionally before - Signals something is about to happen. Name always include the word will.
    Example: applicationWillTerminate:.
  • Unconditionally after - Signals something has happened. Name always include the word did.
    Example: applicationDidFinishLaunching:.
  • Customizers - Request information for how to function. Name includes the information that is required.
    Example tableView:viewForHeaderInSection:.

所有委托方法始终将其发送者作为参数之一.任何委托方法都可能具有改变发送者行为方式的返回值.

All delegate methods always have their sender as one of the arguments. Any delegate method may have a return value that alters how the sender behaves.

这篇关于对Objective-C中的委托有点困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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