2011-01-08 63 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]; 
}