委托iOS的多个侦听器

时间:2013-10-19 10:21:50

标签: ios

我有一个带有委托didSelectString的类搜索栏。我有一个实现委托的类A和一个实现委托的类B.

但是只执行A类的委托。代表可以有多个听众吗?以及如何实现这个

3 个答案:

答案 0 :(得分:14)

委派是一种单一的消息传递协议。如果要向更改的多个对象发送消息,则需要使用NSNotifications。

您可以使用通知中心传递对象:

NSDictionary *userInfo = @{@"myObject" : customObject};

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"myNotificationString" object:self userInfo:userInfo];

想要收听通知时

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myCustomObserver:)name:@"myNotificationString" object:nil];

设置选择器

-(void)myCustomObserver:(NSNotification *)notification{
    CustomObject* customObject = notification.userInfo[@"myObject"];
}

答案 1 :(得分:3)

您可以轻松设置充当委托多路复用器的trampoline对象。我们的想法是使用一个代理对象来代替一组代理。调用方法时,它将覆盖 forwardInvocation 或使用 * IMP_implementationWithBlock * 将消息传递给数组中的每个代理。

然后您需要做的就是添加方法:attachListener和removeListener(顺便说一句:看看它是如何开始与通知类似的?)

以下是一个示例项目:https://github.com/aleph7/MultiDelegate

有关更多信息,请查看令人敬畏的Objective-C运行时:https://developer.apple.com/library/mac/documentation/cocoa/reference/objcruntimeref/Reference/reference.html

答案 2 :(得分:1)

创建一个名为Delegates的小型新类。它采用搜索栏协议​​,因此它可以是主要的搜索栏代表。让这个类提供一个方法'addSearchBarDelegate:',它将委托添加到一个可变数组。当它获得委托消息时,它会将其转发给每个注册的委托。

相关问题