Search only matching words at the beginning

In one example code from Apple, they provide an example search:

for (Person *person in personsOfInterest) { NSComparisonResult nameResult = [person.name compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])]; if (nameResult == NSOrderedSame) { [self.filteredListContent addObject:person]; } } 

Unfortunately, this search will match the text at the beginning. If you are looking for “John,” it will match “John Smith” and “Johnny Rotten,” but not “Peach John” or “John.”

Is there a way to change it to find search text anywhere in the title? Thanks.

+4
source share
2 answers

Try using rangeOfString:options: instead:

 for (Person *person in personsOfInterest) { NSRange r = [person.name rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)]; if (r.location != NSNotFound) { [self.filteredListContent addObject:person]; } } 

Another way you could do this is to use NSPredicate:

 NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", searchText]; //the c and d options are for case and diacritic insensitivity //now you have to do some dancing, because it looks like self.filteredListContent is an NSMutableArray: self.filteredListContent = [[[personsOfInterest filteredArrayUsingPredicate:namePredicate] mutableCopy] autorelease]; //OR YOU CAN DO THIS: [self.filteredListContent addObjectsFromArray:[personsOfInterest filteredArrayUsingPredicate:namePredicate]]; 
+6
source

-[NSString rangeOfString:options:] and friends are what you want. It returns:

" NSRange structure indicating the location and length in the receiver of the first occurrence of aString , modulo the parameters in the mask. Returns {NSNotFound, 0} if aString not found or is empty ( @"" )."

+1
source

All Articles