把书本的代码敲下来,发现搜索的实现就那么几行代码,感叹强大之余,也挺伤脑,一下子太多新东西,又是NSPredicate的、又是NSRange的。。。
下面是两个委托方法,其实还不是很明白,过几天回来看看,或许有新发现。哈哈。
#pragma mark -
#pragma mark Search Display Delegate Methods
- (void)searchDisplayController:(UISearchDisplayController *)controller
didLoadSearchResultsTableView:(UITableView *)tableView
{
[tableView registerClass:[UITableViewCell class]
forCellReuseIdentifier:SectionsTableIdentifier];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[filteredNames removeAllObjects];
if (searchString.length > 0) {
NSPredicate *predicate =
[NSPredicate
predicateWithBlock:^BOOL(NSString *name, NSDictionary *b)
{
//返回name中与searchString匹配的首个串的范围,options指定搜索选项(这个先放放)
NSRange range = [name rangeOfString:searchString
options:NSCaseInsensitiveSearch];
return range.location != NSNotFound;
}];
for (NSString *key in self.keys) {
//按照谓词predicate的规则过滤self.name[key]
NSArray *matches = [self.names[key]
filteredArrayUsingPredicate: predicate];
[filteredNames addObjectsFromArray:matches];
} }
return YES;
}
关于options,官方文档直接google翻译:
搜索和比较选项
几个搜索和比较的方法,采取“选项”的说法。这是一个位掩码,进一步增加了限制的操作。您通过结合下列选项(并非所有选项都可供每一个方法)创建蒙版:
正在执行搜索和比较,如果的NSLiteralSearch
选项指定。
Search and Comparison Options
Several of the search and comparison methods take an “options” argument. This is a bit mask that adds further constraints to the operation. You create the mask by combining the following options (not all options are available for every method):
Search and comparison are currently performed as if the NSLiteralSearch
option were specified.