iOS中的多个代表 [英] Multiple Delegates in iOS

查看:111
本文介绍了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. 切换到Observer模式,您可以注册多个观察者,与。。。相互作用。当你的观察者都实现相同的协议,你的主类想要知道观察者和与他们的交互时,这是有用的。

  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以指示状态更改和事件。这里是一个更加分离的方法,因为主类不需要知道谁在听,不直接与他们进行交互。其他人可以开始和停止在他们的休闲通知。它还具有您不需要创建或实现单独的协议的优点。

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天全站免登陆