1 - (void)viewDidLoad {
2 [super viewDidLoad];
3
4 self.allResults = @[@"Here's", @"to", @"the", @"crazy", @"ones.", @"The", @"misfits.", @"The", @"rebels.", @"The", @"troublemakers.", @"The", @"round", @"pegs", @"in", @"the", @"square", @"holes.", @"The", @"ones", @"who", @"see", @"things", @"differently.", @"They're", @"not", @"fond", @"of", @"rules.", @"And", @"they", @"have", @"no", @"respect", @"for", @"the", @"status", @"quo.", @"You", @"can", @"quote", @"them,", @"disagree", @"with", @"them,", @"glorify", @"or", @"vilify", @"them.", @"About", @"the", @"only", @"thing", @"you", @"can't", @"do", @"is", @"ignore", @"them.", @"Because", @"they", @"change", @"things.", @"They", @"push", @"the", @"human", @"race", @"forward.", @"And", @"while", @"some", @"may", @"see", @"them", @"as", @"the", @"crazy", @"ones,", @"we", @"see", @"genius.", @"Because", @"the", @"people", @"who", @"are", @"crazy", @"enough", @"to", @"think", @"they", @"can", @"change", @"the", @"world,", @"are", @"the", @"ones", @"who", @"do."];
5
6 self.visibleResults = self.allResults;
7 }
1 - (void)setFilterString:(NSString *)filterString {
2 _filterString = filterString;
3
4 if (!filterString || filterString.length <= 0) {
5 self.visibleResults = self.allResults;
6 }
7 else {
8 NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"self contains[c] %@", filterString];
9 self.visibleResults = [self.allResults filteredArrayUsingPredicate:filterPredicate];
10 }
11
12 [self.tableView reloadData];
13 }
从上述代码可以看到,APPLE获取到模糊搜索结果所用的代码仅仅两行。由此可见,NSPredicate的功能不可小觑。这也是本文的目的,全方位地介绍一下在cocoa框架下的搜索匹配利器:NSPredicate。Cocoa框架中的NSPredicate用于查询,原理和用法都类似于SQL中的where,作用相当于数据库的过滤取。