对Objective-C的代表很少感到困惑 [英] Little confused on Delegates in Objective-C

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

问题描述

我知道一个Objective-C的好东西,我正在使用一个iPhone SDK书(来自刚刚做过控制台程序的Obj-C书)。它试图解释代表们,虽然它被冲上了,并没有真正了解它正在试图传达什么。我有点困惑,他们是什么,什么时候使用它们。



基本上它表示,他们是负责代表另一个对象做某些事情的类。



任何人都关心细节?



谢谢!

解决方案

依赖关系。在大多数框架中,客户端会将所需的依赖项注入到实例中,通常在构造函数或setter中。



可可做相反;



代理方法有四种主要类型:




  • 有条件地在之前 - 发出信号即将发生,但代表可能会中止。名称总是包含单词Should。

    示例: searchBar 应该 EndEditing:

  • 无条件之前 - 信号将要发生。名称总是包含单词will。

    示例:应用程序 终止:

  • 无条件地 - 发出信号。名称总是包括这个词。

    示例:应用程序 没有 FinishLaunching:

  • 定制程序 - 请求有关如何运行的信息。名称包括所需的信息。

    示例 tableView: viewForHeaderInSection



所有委托方法始终将其发件人作为论点。任何代理方法都可能有一个返回值来改变发送方的行为。


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.

Anyone care to elaborate?

Thanks!

解决方案

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:

  • 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天全站免登陆