I have a table view display rows by person's name property. The table view allows user to fussy search by name. e.g. if user types in 'crp' it would match the name 'Chris Paul'.
I have a method that takes a search string and setup NSPredicate to search model's name in an array
- (void)setPredicateWithText: (NSString *)searchText
{
for (int i = 0; i < searchText.length; i ++)
{
NSString *character = [searchText substringWithRange:NSMakeRange(i, 1)];
self.format = [self.format stringByAppendingFormat:@".*%@",character];
if (i == searchText.length -1) // last character
{
self.format = [self.format stringByAppendingString:@".*"];
}
}
// result format == .*c.*r.*p.*
self.searchPredicate = [NSPredicate predicateWithFormat:@"SELF.name MATCHES '%@'", self.format];
}
and in other method:
self.resultArray = [self.allPlayers filteredArrayUsingPredicate:self.searchPredicate];
but nothing comes back as result... please help me, thanks!!
There are two things you should change in your code,
1) replace '%@' with %@
2) add [c] to ignore the case sensitivity
The predicate should be like this,
[NSPredicate predicateWithFormat:@"SELF.name MATCHES [c] %@", self.format];
finally the method,
- (void)setPredicateWithText: (NSString *)searchText
{
for (int i = 0; i < searchText.length; i ++)
{
NSString *character = [searchText substringWithRange:NSMakeRange(i, 1)];
self.format = [self.format stringByAppendingFormat:@".*%@",character];
if (i == searchText.length -1) // last character
{
self.format = [self.format stringByAppendingString:@".*"];
}
}
// result format == .*c.*r.*p.*
self.searchPredicate = [NSPredicate predicateWithFormat:@"SELF.name MATCHES [c] %@", self.format];
}