委派给多个对象 [英] Delegation to multiple objects

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

问题描述

在Objective-C中是否可以一次委派给两个对象?我知道委派模式意味着一次响应,对于多个侦听器和广播,有通知中心,但通知不返回任何值.

Is there any way to delegate to two objects at a time in Objective-C? I know that delegation pattern implies one response at a time and for multiple listeners and broadcasting there is notification center but notification does not return any value.

如果我有一个基于网络的大量iOS项目,并且需要委派给多个侦听器并要求从它们返回值,那么在这种情况下,哪种方法最好?

If I have a heavily network-based iOS project and need to delegate to multiple listeners and required to return values from them, in this scenario what approach should be the best?

推荐答案

在每个类中,委托都是一个委托,因此会通知一位委托有关该事件的信息.但是,没有什么禁止您声明带有一组委托的类.

In every class the delegate is one, so one delegate is informed about the event. But nothing forbids you to declare a class with a set of delegates.

或改为使用观察.一个类可以被多个类观察.

Or use Observation instead. A class may be observed by multiple classes.

示例

根据OP的要求,由于一些代码也将很有用,因此可以采用以下方法:

As requested from the OP, since also some code would be useful, here is a way of doing it:

@interface YourClass()

@property (nonatomic, strong, readwrite) NSPointerArray* delegates;
// The user of the class shouldn't even know about this array
// It has to be initialized with the NSPointerFunctionsWeakMemory option so it doesn't retain objects

@end  

@implementation YourClass

@synthesize delegates;

...   // other methods, make sure to initialize the delegates set with alloc-initWithOptions:NSPointerFunctionsWeakMemory

- (void) addDelegate: (id<YourDelegateProtocol>) delegate
{
    [delegates addPointer: delegate];
}

- (void) removeDelegate: (id<YourDelegateProtocol>) delegate
{
    // Remove the pointer from the array
    for(int i=0; i<delegates.count; i++) {
        if(delegate == [delegates pointerAtIndex: i]) {
            [delegates removePointerAtIndex: i];
            break;
        }
    } // You may want to modify this code to throw an exception if no object is found inside the delegates array
}

@end

这是一个非常简单的版本,您可以用另一种方式来做.我不建议公开代表集,您永远都不知道如何使用它,并且可能会获得不一致的状态,尤其是在多线程处理中.另外,添加/删除委托时,可能需要运行其他代码,这就是将委托设置为私有的原因. 您可能还会有很多其他方法,例如delegatesCount.

This is a very simple version, you can do it in another way. I don't suggest to make public the delegates set, you never know how it could be used, and you can get an inconsistent state, specially with multithreading. Also, when you add/remove a delegate you may need to run additional code, so that's why making the delegates set private.
You may also a lot of other methods like delegatesCount for example.

PS:该代码已被编辑为 NSPointerArray 而不是 NSMutableSet ,因为如注释中所述,委托应使用弱指针保存,以避免保持循环.

PS: The code has been edited to be a NSPointerArray instead of a NSMutableSet, because as stated in the comments a delegate should be held with a weak pointer to avoid retain cycles.

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

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