objective-c - 委托(delegate)给多个对象

标签 objective-c

有没有办法在 Objective-C 中一次委托(delegate)给两个对象?我知道委托(delegate)模式意味着一次一个响应,对于多个听众和广播,有通知中心,但通知不返回任何值。

如果我有一个高度基于网络的 iOS 项目并且需要委托(delegate)给多个监听器并需要从它们返回值,在这种情况下哪种方法应该是最好的?

最佳答案

在每个类中,委托(delegate)都是一个,因此一个委托(delegate)被告知事件。但是没有什么可以禁止您使用一组委托(delegate)来声明一个类。

或者改用 Observation。一个类(class)可能被多个类(class)观察。

示例

根据 OP 的要求,由于一些代码也很有用,这里有一种方法:

@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

这是一个非常简单的版本,你可以用另一种方式来做。我不建议公开委托(delegate)集,你永远不知道它是如何使用的,而且你可能会得到一个不一致的状态,特别是在多线程中。此外,当您添加/删除委托(delegate)时,您可能需要运行额外的代码,因此这就是将委托(delegate)设置为私有(private)的原因。 您还可以使用许多其他方法,例如 delegatesCount

PS:代码已被编辑为 NSPointerArray 而不是 NSMutableSet,因为如注释中所述,委托(delegate)应使用弱指针来避免保留周期。

关于objective-c - 委托(delegate)给多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14278857/

相关文章:

iphone - 是removeFromSuperview释放了对象吗?

iOS,钥匙串(keychain) : Wrong passcode output

iphone - 传递参数使指针来自整数而不进行强制转换

objective-c - iOS使用色轮选择颜色

ios - cellForRowAtIndexPath : not called by reloaddata

objective-c - 将 NSNumber 分配给 NSString

objective-c - 在 swift 中从前缀 header 引用类定义

objective-c - __typeof self 在 Objective-C 泛型中?

ios - CoreSpotlight 缩略图图像未显示在 Spotlight 搜索中

iphone - 将 UITextView 限制为一行