Cocoa Touch中的代表与事件 [英] Delegates vs. events in Cocoa Touch

查看:85
本文介绍了Cocoa Touch中的代表与事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写我的第一个iPhone应用程序,我一直在探索Cocoa Touch和Objective-C的设计模式。我来自客户端web开发的背景,所以我试图包装代表。



具体来说,我不知道为什么委托对象而不是事件处理程序。例如,当用户按下按钮时,用事件( UITouchUpInside )处理它,但是当用户完成输入到文本框并且用完成'按钮,通过调用文本框的委托( textFieldShouldReturn )上的方法来处理操作。



一个委托方法而不是一个事件?我也注意到在视图控制器与 viewDidLoad 方法。为什么不只是使用事件?

解决方案

编辑:另一个好的帖子:
NSNotificationCenter与委派(使用协议)?



委托是回调所以有1:1的关系。委托是实现正式协议的对象的单个实例。



通知(事件)基本上广播到许多对某事发生感兴趣的对象。 p>

代理能够将代码插入到一些其他对象的处理流程中,例如回调之前和之后,为控件提供数据源以及在视图之间进行通信; p>



因此,代理与对象有更紧密的关系,因为它们是单个提供的对象来插入和改变处理对象或提供数据。你推迟决定和外部操作,如加载数据到一些其他对象 - 这就是为什么它是一个非常普通的模式的通用UIKit类。通知其他对象是一个更宽松的关系 - 只是一个通知他人发生了一些事情。



这也不是一个vs问题。例如,你可以有一个应用程序做后台处理,它发出了一个更改的通知,导致视图调用其数据源代理刷新其视图。它们是两种不同的机制。


I'm writing my first iPhone app, and I've been exploring the design patterns in Cocoa Touch and Objective-C. I come from a background of client-side web development, so I'm trying to wrap my head around delegates.

Specifically, I don't see why delegate objects are needed instead of event handlers. For instance, when the user presses a button, it is handled with an event (UITouchUpInside), but when the user finishes inputting to a text box and closes it with the 'Done' button, the action is handled by calling a method on the text box's delegate (textFieldShouldReturn).

Why use a delegate method instead of an event? I also notice this in the view controller with the viewDidLoad method. Why not just use events?

解决方案

EDIT: Another good post: NSNotificationCenter vs delegation( using protocols )?

A delegate is a callback so there is a 1:1 relationship. The delegate is a single instance of an object that implements a formal protocol.

Notifications (events) are basically broadcasts to many objects that are interested in when something happens.

Delegates are good for being able to interject code into the pipeline of some other objects processing such as before and after callbacks, providing data sources for a control and communicating between views:

What exactly does delegate do in xcode project?

Therefore delegates have a much tighter relationship with the object since they are the single provided object to interject and alter processing of the object or provide data. You're deferring decisions and external operations like loading data to some other object - which is why it's a very common pattern for generic UIKit classes. Notifications to other objects is a much looser relationship - it just that a notifies others that something happened.

It's also not a "vs" question necessarily. For example you could have an app that does background processing and it fired a something changed notification causing a view to call its data source delegate to refresh its view. They are two different mechanisms.

这篇关于Cocoa Touch中的代表与事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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