开发者

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 controlle开发者_如何学运维r that instances the search display controller can be the delegate of the search bar and know if text has changed?


@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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜