且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Objective-C库中回调的选择器或块

更新时间:2022-11-23 10:02:34

个人而言,我讨厌使用代理。因为C的结构是如何客观化的,所以它真的搞砸了代码如果我必须创建一个单独的对象/添加一个协议,只是为了被通知你的一个事件,我必须实现5/6。因此,我更喜欢块。

Personally, I hate using delegates. Because of how objective-C is structured, It really clutters code up If I have to create a separate object / add a protocol just to be notified of one of your events, and I have to implement 5/6. For this reason, I prefer blocks.

尽管他们(块)确实有其缺点(e.x.内存管理可能很棘手)。它们易于扩展,易于实现,并且在大多数情况下仅仅是有意义的。

While they (blocks) do have their disadvantages (e.x. memory management can be tricky). They are easily extendable, simple to implement, and just make sense in most situations.

尽管苹果的设计结构可能使用发送者 - 委托方法,这只是为了向后兼容。最近的Apple API一直在使用block(e.x. CoreData),因为它们是Objective-C的未来。虽然它们可以在使用过程中混乱代码,但它也允许更简单的匿名代理,这在目标C中是不可能的。

While apple's design structures may use the sender-delegate method, this is only for backwards compatibility. More recent Apple APIs have been using blocks (e.x. CoreData), because they are the future of objective-c. While they can clutter code when used overboard, it also allows for simpler 'anonymous delegates', which is not possible in objective C.

最后,它真的很由此可见:
您是否愿意放弃一些较旧的,更加日久的平台,以换取使用块与代表?代表的一个主要优点是:保证可以在任何版本的objc-runtime中运行,而块是该语言的最新补充。

In the end though, it really boils down to this: Are you willing to abandon some older, more dated platforms in exchange for using blocks vs. a delegate? One major advantage of a delegate is that it is guaranteed to work in any version of the objc-runtime, whereas blocks are a more recent addition to the language.

至于 NSNotificationCenter / KVO 是关心的,它们都是有用的,有其目的,但作为代表,它们并不意图被使用。也不能将结果发送给发件人,并且在某些情况下,这是至关重要的(例如, -webView:shouldLoadRequest:)。

As far as NSNotificationCenter/KVO is concerned, they are both useful, and have their purposes, but as a delegate, they are not intended to be used. Neither can send a result back to the sender, and for some situations, that is vital (-webView:shouldLoadRequest: for example).