Objective C委托还是C风格的块回调? [英] Objective C delegate or C-style block callback?

查看:184
本文介绍了Objective C委托还是C风格的块回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个类,只要发生某事,它就会触发事件。这些事件往往与非UI相关。我想知道这样做的最佳方法是什么。我一直在探索:

I am designing a class that will "fire events" whenever something occurs. These events tend to be non-UI related. I'm wondering what the best method for doing so is. I've been exploring either:

代表

我将定义一个委托类,接受init函数中的委托,并在事件发生时调用委托类上的方法。

I'll define a delegate class, accept a delegate in the init function, and call the methods on the delegate class when an event occurs.

C样式块

我将定义一个函数指针,并在init函数中接受一个函数。我会在事件发生时调用它。

I'll define a function pointer, and accept a function in the init function. I'll call it when an event occurs.

在这两种情况下,我可能需要处理多个源,所以我需要一个委托或块数组。

In both cases, I may need to handle multiple "sources" so I'll need an array of delegates or blocks.

我注意到在iOS编程中,代表往往更喜欢UI框架。但是我来自函数编程背景,我非常适合接受函数点并在调用站点传递lambdas,我喜欢编译器为你处理吊装变量,你通常需要较少的类状态。但是我看到很多iOS开发人员正在使用代理。

I've noticed that in iOS programming, delegates tend to be preferred especially for UI frameworks. But I come from a functional programming background where I definitely am comfortable with accepting function points and passing lambdas at the call site, and I like that the compiler handles hoisting variables for you, and you generally need less class-state. But I see that a lot of iOS developers are using delegates.

iOS中通常首选的机制是什么?

What is the generally preferred mechanism in iOS for doing this?

推荐答案

每个都有它的用途。

当有多个事件告诉代表时,应该使用代理关于和/或何时类需要从委托中获取数据。一个很好的例子是 UITableView

Delegates should be used when there are multiple "events" to tell the delegate about and/or when the class needs to get data from the delegate. A good example is with UITableView.

当只有一个(或两个)时,最好使用一个块事件。完成块(可能是故障块)就是一个很好的例子。一个很好的例子是 NSURLConnection sendAsynchronousRequest:queue:completionHandler:

A block is best used when there is only one (or maybe two) event. A completion block (and maybe a failure block) are a good example of this. A good example is with NSURLConnection sendAsynchronousRequest:queue:completionHandler:.

第三个选项是通知。当事件中可能存在多个(和未知的)相关方时,最好使用此方法。其他两个仅在有一个(和已知的)感兴趣方时才有用。

A 3rd option is notifications. This is best used when there are possibly multiple (and unknown) interested parties in the event(s). The other two are only useful when there is one (and known) interested party.

这篇关于Objective C委托还是C风格的块回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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