1

我想改进我的研究UITableViewController。现在我有一个NSMutableArray这样的:

    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"the dog is brown",@"the cat is red",@"the mouse is grey"];

现在如果我在我searchbar的例子中写:“猫”,表格将显示“猫是红色的”,没关系。但是如果我写:“cat red”,表格就会是空的。

我能做些什么来改善这一点?

所以就像现在进行搜索一样:

-(void)loadArray {

  arraySearch = [[NSMutableArray alloc] initWithCapacity:[array count]];
  [arraySearch addObjectsFromArray: array]; 
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

  [arraySearch removeAllObjects];

  for (int z=0; z<[array count]; z++) {

    if ([[array objectAtIndex:z] rangeOfString:searchText options:NSCaseInsensitiveSearch].location !=NSNotFound) {

        [arraySearch addObject:[array objectAtIndex:z]];
    }

      [self.tableView reloadData];

}

谢谢大家。

我找到了解决方案,我想与您分享

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

 [arraySearch removeAllObjects];

  NSArray *listItems = [searchText componentsSeparatedByString:@" "];


NSMutableArray *arrayPredicate = [NSMutableArray array];
for (NSString *str in listItems) {

    if ([str length] > 0) {
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"self contains [cd] %@ OR self contains [cd] %@", str, str];
        [arrayPredicate addObject:pred];
    }
}

NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:arrayPredicate];

[arraySearch addObjectsFromArray:[array filteredArrayUsingPredicate:predicate]];


[self.tableView reloadData];

}
4

1 回答 1

1
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

    [arraySearch removeAllObjects];

    //Break the sentence into words
    NSArray *listItems = [searchText componentsSeparatedByString:@" "];

    //Iterate each word and create predicate statement
    NSMutableArray *predicatesArray = [NSMutableArray array];
    for (NSString *str in listItems) {
        [predicatesArray addObject:[NSString stringWithFormat:@"SELF like[c] %@",str]];
    }

    //Concatenate predicate statements by conditional OR
    NSPredicate* predicate = [NSPredicate predicateWithFormat:[predicatesArray componentsJoinedByString:@" OR "]];

    //Filter the array against matching predicate
    [arraySearch addObjectsFromArray:[array filteredArrayUsingPredicate:predicate]];

    [self.tableView reloadData];

}
于 2013-09-16T13:06:16.480 回答