iOS 中的多个委托 [英] Multiple Delegates in iOS

查看:18
本文介绍了iOS 中的多个委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个对象,用于为我的所有视图控制器下载内容.该对象是单例实例,下载完成后有一个回调方法接收数据.它还有一个委托属性,以便它知道在下载完成后回调哪个对象.

I am making an object that goes to download stuff for all of my view controllers. The object is singleton instance and has a callback method with received data once the download is completed. It also has a delegate property so that it knows which object to call back to after the download is done.

有多个控制器使用这个共享实例,我的问题是如何回调请求下载的正确视图控制器.

There are multiple controllers that use this shared instance, and my question is how to call back to the correct view controller that requested the download.

我的方法是使用委托,但问题是由于其他视图控制器也是它的委托,下载对象可能会回调到每个对象,这将很难跟踪.

My approach is to use delegation, but the problem is that since other view controllers are also its delegate, the download object could call back to every object and this will be hard to track.

推荐答案

我曾在一些项目中工作,人们试图使用多个委托,但这基本上是一个坏主意.委托模式是一个类和它的委托之间的一对一关系.虽然可以通过切换委托实现某种程度的多重委托,但更有可能导致不可预测的行为和错误.

I've worked on projects where people have attempted to use multiple delegates and it's basically a bad idea. The delegate pattern is about a 1 to 1 relationship between a class and it's delegate. Whilst it is possible to achieve some level of multiple delegation through switching the delegates in and out, it's more likely to lead to unpredictable behaviour and bugs.

我的建议是改变您对此的看法.在我看来,您有两个选择:

My recommendation would be to change how you are thinking about this. You have two options as I see it:

  1. 切换到观察者模式,您可以在其中注册主类可以与之交互的多个观察者.当您的观察者都实现相同的协议并且您的主类想要了解观察者并与他们进行交互时,这很有用.

  1. Switch to an Observer pattern where you can register multiple observers which your main class can interact with. This is useful where your observers all implement the same protocol and where your main class wants to be aware of the observers and interaction with them.

广播 NSNotifications 以指示状态更改和事件.这是一种更加解耦的方法,因为主类不需要知道谁在听,也不直接与他们交互.其他人可以在闲暇时开始和停止收到通知.它还具有您不需要创建或实施单独协议的优点.相反,您可以向 NSNotificationCenter 注册需要了解更改的类,NSNotificationCenter 反过来为您处理所有通知路由.

Broadcast NSNotifications to indicate state changes and events. Here is a more decoupled approach because the main class does not need to know who is listening and does not directly interact with them. Other can start and stop being notified at their leisure. It also has the advantage that you do not need to create or implement a separate protocol. Instead you register the classes that need to know about changes with the NSNotificationCenter which in turns handles all the routing of notifications for you.

这篇关于iOS 中的多个委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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