Ilario
Ilario

Reputation: 6079

Improve search in UISearchDisplayController

I would like to improve research within my UITableViewController. Now i have an NSMutableArray like this:

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

Now if I write in my searchbar for example: "the cat", the table will show "the cat is red" and it is ok. But if I write: "cat red", the table will be empty.

What can I do to improve this?

so it becomes like making the search now:

-(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];

}

Thanks to all.

I FOUND the solution and I would like to share it with you:

-(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];

}

Upvotes: 1

Views: 204

Answers (1)

Syed Absar
Syed Absar

Reputation: 2284

-(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];

}

Upvotes: 1

Related Questions