您的位置:首页 > 移动开发 > IOS开发

iOS中非常强大的过滤器:NSPredicate

2015-09-15 17:56 477 查看
在APPLE的官方Demo:UICatalog中实现UISearchBar模糊搜索功能是这么做的:
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.", @"<
4000
/span>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 }
其中,self.allResults是列表的全部结果,self.visibleResults是输入搜索词后出现的模糊匹配结果。流程如下图所示:从上述代码可以看到,APPLE获取到模糊搜索结果所用的代码仅仅两行。由此可见,NSPredicate的功能不可小觑。这也是本文的目的,全方位地介绍一下在cocoa框架下的搜索匹配利器:NSPredicate。Cocoa框架中的NSPredicate用于查询,原理和用法都类似于SQL中的where,作用相当于数据库的过滤取。1、初始化
那传入的初始化NSString到底要满足怎样的格式呢?
2、使用2.1 场景1:NSArray过滤,也就是文章开头的场景
2.2 场景2:判断字符串首字母是否为字母
2.3 场景3:字符串替换
2.4 场景4:截取字符串
2.5 场景5:判断是否是手机号码或者电话号码
2.6 场景6:验证邮箱、电话号码有效性
2.7 场景7:NSDate筛选
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: