2011-03-22 49 views
0

有沒有辦法讓多個對象偵聽UISearchbBar實例的void委託方法?多個代表收聽uisearchbar的一個實例

例如,如何UISearchDisplayController知道搜索條具有其文本串中改變:

– searchDisplayController:shouldReloadTableForSearchString: 

而在同一時間實例中,搜索顯示控制器可搜索的代表表視圖控制器酒吧,並知道文字是否改變?

回答

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 

然後,只需設置一個MultiplexingSearchBarDelegateUISearchBar的代表,並直接添加委託給MultiplexingSearchBarDelegate而不是向UISearchBar

0

只有一個對象可以是委託並接收委託方法調用。然而,委託可以通過你寫的委託協議來通知許多對象。你可能需要重構一下。