prostock
prostock

Reputation: 9545

more than one delegate listen to an instance of uisearchbar

Is there a way for more than one object to listen to void delegate methods of an instance of UISearchbBar?

For example, how does UISearchDisplayController know the search bar has its text string changed in:

– searchDisplayController:shouldReloadTableForSearchString:

While at the same time the table view controller that instances the search display controller can be the delegate of the search bar and know if text has changed?

Upvotes: 0

Views: 380

Answers (2)

aroth
aroth

Reputation: 54846

@interface MultiplexingSearchBarDelegate : NSObject<UISearchBarDelegate> {
    NSMutableArray* delegates;
}

- (void) addDelegate: (id) theDelegate;
- (void) removeDelegate: (id) theDelegate;
@end

@implementation MultiplexingSearchBarDelegate

- (id) init {
    if ((self = [super init])) {
        delegates = [[NSMutableArray alloc] initWithCapacity: 16];
    }
}

- (void) dealloc {
    [delegates release];
    [super dealloc]
}

- (void) addDelegate: (id) theDelegate {
    @synchronized(delegates) {
        if (theDelegate && ! [delegates containsObject: theDelegate]) {
            [delegates addObject: theDelegate];
        }
    }
}

- (void) removeDelegate: (id) theDelegate {
    @synchronized(delegates) {
        if (theDelegate && [delegates containsObject: theDelegate]) {
            [delegates removeObject: theDelegate];
        }
    }
}

//add your UISearchBarDelegate methods here, following a pattern like this
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    @synchronized(delegates) {
        for (id<UISearchBarDelegate> theDelegate in delegates) {
            [theDelegate searchBar:searchBar textDidChange:searchText];
        }
    }
}

@end

Then just set a MultiplexingSearchBarDelegate as the delegate of the UISearchBar, and add your delegates to the MultiplexingSearchBarDelegate instead of directly to the UISearchBar.

Upvotes: 3

user189804
user189804

Reputation:

Only one object can be the delegate and receive the delegate method calls. However the delegate can notify an many objects as you like, perhaps via delegate protocols you have written. You probably need to refactor a bit.

Upvotes: 0

Related Questions