2011-01-08 62 views
2

我試圖在tableview中插入一個搜索欄,它是從數組的NSDictionary中加載信息。每個數組擁有和對象。每個對象都有幾個屬性,例如Name或Address。UISearchBar - 搜索對象數組的NSDictionary

我已經實現了NSSearchBar的方法,但代碼對應於搜索它自己,我有另一個項目,其中數組只有字符串,不工作,我不能解決問題。

代碼如下: 'indiceLateral'是一個帶有字母的數組; 'partners'是一個NSDictionary; 'RLPartnersClass'是我的一類合作伙伴,每一個都有屬性(名稱,地址,...)。

-(void)handleSearchForTerm:(NSString *)searchTerm { 

NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init]; 
[self resetSearch]; 

for (NSString *key in self.indiceLateral) { 
    NSMutableArray *array = [partners valueForKey:key]; 
    NSMutableArray *toRemove = [[NSMutableArray alloc] init]; 

    for (NSString *name in array) { 
    if ([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound) 
    [toRemove addObject:name]; 
    } 

    if ([array count] == [toRemove count]) 
    [sectionsToRemove addObject:key]; 
    [array removeObjectsInArray:toRemove]; 
    [toRemove release]; 
} 

[self.indiceLateral removeObjectsInArray:sectionsToRemove]; 

[sectionsToRemove release]; 
[theTable reloadData]; 
} 

任何人都可以幫助我嗎?

感謝,

銳洛佩斯

回答

5

我已經做到了。

實施例:

-(void)handleSearchForTerm:(NSString *)searchTerm { 

    NSMutableDictionary *finalDict = [NSMutableDictionary new]; 
    NSString *currentLetter = [[NSString alloc] init]; 

    for (int i=0; i<[indiceLateral count]; i++) { 
     NSMutableArray *elementsToDict = [[[NSMutableArray alloc] init] autorelease]; 
     currentLetter = [indiceLateral objectAtIndex:i]; 

     NSArray *partnersForKey = [[NSArray alloc] initWithArray:[partnersCopy objectForKey:[indiceLateral objectAtIndex:i]]]; 

     for (int j=0; j<[partnersForKey count]; j++) { 
      RLNames *partnerInKey = [partnersForKey objectAtIndex:j]; 

      NSRange titleResultsRange = [partnerInKey.clientName rangeOfString:searchTerm options:NSDiacriticInsensitiveSearch | NSCaseInsensitiveSearch]; 

      if (titleResultsRange.length > 0){ 
       NSLog(@"found: %@", partnerInKey.clienteCity 
       [elementsToDict addObject:partnerInKey]; 
      } 
     } 

     [finalDict setValue:elementsToDict forKey:currentLetter]; 
    } 

    NSMutableDictionary *finalResultDict = [finalDict mutableDeepCopy]; 
    self.partners = finalResultDict; 
    [finalResultDict release]; 

    [theTable reloadData]; 
}