委托iOS的多个侦听器

jon*_*len 10 ios

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

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

Dav*_*ong 15

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

您可以使用通知中心传递对象,如下所示:

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

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"myNotificationString" object:self userInfo:userInfo];
Run Code Online (Sandbox Code Playgroud)

想要收听通知时

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myCustomObserver:)name:@"myNotificationString" object:nil];
Run Code Online (Sandbox Code Playgroud)

并设置选择器

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

  • 不要忘记在释放时调用removeObserver (3认同)