是否有办法让多个对象侦听UISearchbBar实例的void委托方法?
例如,UISearchDisplayController如何知道搜索栏的文本字符串已更改:
– searchDisplayController:shouldReloadTableForSearchString:
同时在表视图控制器中,搜索显示控制器的实例可以是搜索栏的代理并知道文本是否已更改?
答案 0 :(得分:4)
@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
然后只需设置一个MultiplexingSearchBarDelegate
作为UISearchBar
的代表,并将您的代表添加到MultiplexingSearchBarDelegate
,而不是直接添加到UISearchBar
。
答案 1 :(得分:0)
只有一个对象可以作为委托并接收委托方法调用。但是,代理可以根据您的喜好通知许多对象,也许可以通过您编写的委托协议。你可能需要重构一下。