Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple listeners for delegate iOS

Tags:

ios

I have a class search bar with a delegate didSelectString. I have an class A that implements the delegate and a class B that implements the delegate.

However only the delegate from class A is executed. Can a delegate have multiple listeners? and how do I implement this

like image 575
jonas vermeulen Avatar asked Oct 19 '13 10:10

jonas vermeulen


3 Answers

The delegation is a single messaging protocol. You'll need to use NSNotifications if you want to message multiple objects of a change.

You can pass an object using notifications centre like so:

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

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

When wanting to listen for notifications

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

And setting up the selector

-(void)myCustomObserver:(NSNotification *)notification{
    CustomObject* customObject = notification.userInfo[@"myObject"];
}
like image 102
David Wong Avatar answered Oct 14 '22 02:10

David Wong


You can easily set up a trampoline object that acts as a delegate multiplexer. The idea is to use a proxy object that will stand-in for an array of delegates. When a method is invoked, it will override forwardInvocation or use *IMP_implementationWithBlock* to pass the message on to each of the delegates in the array.

Then all you need to do is add methods: attachListener and removeListener (btw: see how this is starting to get similar to notifications?)

Here's a sample project: https://github.com/aleph7/MultiDelegate

For more information check out the awesome Objective-C Runtime: https://developer.apple.com/library/mac/documentation/cocoa/reference/objcruntimeref/Reference/reference.html

like image 36
Jasper Blues Avatar answered Oct 14 '22 02:10

Jasper Blues


Create a small new class called Delegates. Have it adopt the search bar protocol so it can be the primary search bar delegate. Have this class offer a method 'addSearchBarDelegate:', in which it will add the delegate to a mutable array. When it gets a delegate message, it forwards it to each registered delegate.

like image 29
David H Avatar answered Oct 14 '22 04:10

David H