有人可以用Objective-C解释代表吗? [英] Can someone please explain delegates in objective-c?

查看:118
本文介绍了有人可以用Objective-C解释代表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用Objective-C一段时间,几乎了解其大部分功能。不过,代表们的概念不包括我。 有人可以简明扼要地说明什么代表,iPhone SDK中使用的方式,以及我如何最好地利用自己的代码?

I have been using Objective-C for a while and pretty much understand most of its features. However, the concept of delegates eludes me. Can someone please give a succinct and easy to comprehend explanation of what delegates are, how they are used in the iPhone SDK, and how I can best make use of them in my own code?

谢谢!

推荐答案

在目标中使用代理的几个主要原因-C,这是微妙的不同:

There are a couple main reasons to use delegates in Objective-C, which are subtly different:


  1. 增强框架类的基本功能。例如,一个UITableView是非常无聊的,所以你可以给它一个委托来处理有趣的位(创建表单元格,添加文本到段标题,你有什么)。这样,UITableView永远不会改变,但不同的表视图可以看起来和作用非常不同。

  1. Enhancing the base functionality of a framework class. For example, a UITableView is pretty boring on its own, so you can give it a delegate to handle the interesting bits (creating table cells, adding text to section headers, what have you). This way, UITableView never changes, but different table views can look and act very differently.

与依赖关系层次结构中的父对象进行通信。例如,您可能会看到一个按钮,用户可能会推送某些影响其他视图的操作。该视图必须向其父视图或视图控制器发送消息,以便可以创建或销毁或修改其他视图。为了做到这一点,你可以将父对象传递给你的视图,很可能通过一个协议,作为一个弱参考(在Objective-C中,一个赋值属性)。该视图然后可以将协议中声明的任何消息发送到父级或委托对象。

Communicating to parent objects in your dependency hierarchy. For example, you may have a view with a button that the user may push to do something that affects other views. The view will have to send a message to its parent view, or perhaps the view controller, so that it can create or destroy or modify other views. To do this you'd pass the parent object into your view, most likely through a protocol, as a weak reference (in Objective-C, an assign property). The view could then send any message declared in the protocol to the parent, or delegate, object.

此方法需要不涉及意见。例如NSURLConnection将事件传回给它的委托,它可能是使用这种机制创建它的对象。

This approach need not involve views. For example NSURLConnection passes event back to its delegate, which may be the object that created it, using this mechanism.

这篇关于有人可以用Objective-C解释代表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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