块vs代表 [英] Blocks vs Delegates

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

问题描述


可能重复:

代码块完全替代代表?

我刚刚从论坛遇到了以下声明:

I just encountered the following declaration from a forum:


代表是过去,块是未来。

"Delegates is the past. Blocks are the future."

1)是否阻止优先使用方式对委托进行授权任务?


2)使用代理与块有什么特别的好处吗?

1) Are blocks the preferred way to do 'delegation' duties over delegates?
2) Is there any particular benefit of using a delegate vs a block?

推荐答案

p>我认为在代表们做什么和块做什么有一点误会。

I think there's a slight misunderstanding in what delegates do and what blocks do.

在Objective-C中,有三种处理回调的方法:

In Objective-C, there are three ways to handle callbacks:


  1. 委托 - >您将其中一个对象另一个对象的委托,您必须指定生成哪些类型的事件通过父对象,代理对象将响应。

  1. Delegation -> where you make one object the delegate of another object and you have to specify which kinds of events generated by the "parent" object the delegate object will respond to.

Target-Action - > UI交互中的典型代码,其中UI子视图(按钮,滑块,等等)根据预定义的事件处理程序(通常是开发人员指定的一些Objective-C方法)处理的一些用户输入(例如一个触摸/抽头)生成一个事件。

Target-Action -> typical in UI interactions, where a UI subview (button, slider, etc) generates an event based on some user input (for example a touch/tap) that is handled by a predefined event handler (typically some Objective-C method that the developer specifies).

通知 - >一个对象注册一个 NSNotificationCenter 的实例来监听任何类型的事件,并响应一个或多个的这些事件。

Notification -> where an object registers itself with an instance of NSNotificationCenter to "listen" for events of any type and responds to one or more of those events.

块本身不是一种处理委托或任何其他回调的方式。

A block is not by itself a way to handle delegation, or any other callback.

它们是可以访问局部变量和调用方法参数的自包含代码。它们可以用于定义一堆不同上下文中的行为。块的主要优点(正如我所看到的),它可以通过消除无关的过度特定的方法来简化代码,从而使您的代码库混乱。块帮助本地化代码到最有意义的地方:在回调机制内。

They are self-contained pieces of code that have access to the local variables and parameters of the calling method. They can be used to define behavior in a bunch of different contexts. The main benefit of a block (as I see it) is that it can simplify code by eliminating extraneous overly-specific methods that would clutter your codebase. Blocks help to localize code to where it makes the most sense: right there within the callback mechanism.

基本上,使用它们可以提高可读性,并使代码更易维护。

Basically, using them enhances readability and makes code more maintainable.

这些好处是否使块成为首选处理回调的方法绝对是个人意见和经验的问题。 ;)

Whether these benefits make blocks the 'preferred' method of handling callbacks is definitely a matter of personal opinion and experience. ;)

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

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