views:

70

answers:

1

HI, I successfully perform a search within arrayTags with the following code, where arrayTags is the array of a field of each XML element, named "tag". The problem is that, let's say, tag has three words: red, white, blue. If I perform a search "red" or "white, blue", or whatever exactly included in a tag element, everything is OK. But if I search "red white", the search returns nothing. Practically, the search returns results only if I search exactly what is included in the arrayTags, but not non-consecutive words. Do you know how can I solve this problem? Thanks so much!

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


     [resultArray removeAllObjects];

     NSString *cellTitle;
     for (cellTitle in arrayTags){

      NSString *stringa = cellTitle;
      NSRange range = [stringa rangeOfString:searchText];

      NSComparisonResult result = [cellTitle compare:searchText options:NSCaseInsensitiveSearch range:range];
      if (result == NSOrderedSame){

       int posizione = [arrayNames indexOfObjectIdenticalTo:cellTitle];

       [result Array addObject:[arrayNames objectAtIndex:posizione]];


      }
     }

     [self.tableView reloadData];
    }
A: 

Your problem has two or three aspects:

(1) You must define, what is a word separator and what belongs to the word you are looking for. For example, "A, B" can mean, "look for 'A' and 'B'", or it can mean "look for 'A' and '_B'" (undescore indicates the blank) Probably, you want to divide searchText like this:

NSArray *listItems = [searchText componentsSeparatedByCharactersInSet:
                      [characterSetWithCharactersInString:@", "]];

Perhaps, you want to eliminate whitespaces from the listItems objects and empty objects from listItems afterwards.

(2) Only afterwards, you can decide how to look for, what you got from stage (1), for example by creating a predicate which looks for all objects in listItems:

NSPredicate *inPredicate = [NSPredicate predicateWithFormat: @"SELF IN %@",
                           listItems];
NSArray* filteredArray = [arrayTags filteredArrayUsingPredicate:inPredicate];

Note that this predicate is case sensitive, so make your own for other requirements!

(3) filteredArray probably should be a member of your view class and is the new tableDataSource. But, there are a few subtleties to solve: empty search texts, switching the data source from filtered to non-filtered content etc.

Jens