苹果给我们封装好的搜索控件,控件很简单,不过就那个匹配还是需要动点脑子的,我们在搜索的时候肯定有各种匹配规则,下边给的demo就是一个搜索的demo,并且附上谓词的详解。
[objc]view plaincopy
@interfaceViewController ()
{
UISearchBar*mSerchBar;
UITableView*mTableView;
BOOLmIsSearch;
NSArray*mDataArray;
NSArray*mSearchResultArray;
}
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
if(!mSerchBar) {
mSerchBar = [[UISearchBaralloc]initWithFrame:CGRectMake(0,50, [[UIScreenmainScreen]bounds].size.width,50)];
mSerchBar.keyboardType= UIKeyboardTypeDefault;
mSerchBar.showsCancelButton=YES;
mSerchBar.prompt=@"查找图书";
mSerchBar.placeholder=@"请输入图书名称";
mSerchBar.delegate=self;
}
[self.viewaddSubview:mSerchBar];
if(!mTableView) {
mTableView = [[UITableViewalloc]initWithFrame:CGRectMake(0,100, [[UIScreenmainScreen]bounds].size.width,200)style:UITableViewStylePlain];
mTableView.backgroundColor= [UIColorredColor];
mTableView.rowHeight=50;
//mTableView.tableHeaderView = mSerchBar;
mTableView.delegate=self;
mTableView.dataSource=self;
}
[self.viewaddSubview:mTableView];
mIsSearch =NO;
if(!mDataArray) {
mDataArray = [NSArrayarrayWithObjects:@"Java讲义",
@"轻量级Java EE企业应用实战",
@"Android讲义",
@"Ajax讲义",
@"HTML5/CSS3/JavaScript讲义",
@"iOS讲义",
@"XML讲义",
@"经典Java EE企业应用实战"
@"Java入门与精通",
@"Java基础教程",
@"学习Java",
@"Objective-C基础",
@"Ruby入门与精通",
@"iOS开发教程",nilnil];
}
if(!mSearchResultArray) {
mSearchResultArray = [NSArrayarray];
}
/*
谓词表达式由表达式,运算符和值组成
*/
//1.比较运算符 >,<,=(==),<=,>=,!=,BETWEEN; BETWEEN格式为BETWEEN {MIN,MAX},大于等于MIN,小于等于MAX
NSNumber*testNumber =@123;
NSPredicate*pre = [NSPredicatepredicateWithFormat:@"SELF BETWEEN {100,200}"];
if([preevaluateWithObject:testNumber]) {
NSLog(@"%@",testNumber);
}
//2.逻辑运算符 AND(&&),OR(||),NOT(!)
NSArray*testArray = @[@1,@2,@123,@456];
NSPredicate*preLogic = [NSPredicatepredicateWithFormat:@"NOT(SELF > 123 && SELF < 2)"];
NSArray*logicArr = [testArrayfilteredArrayUsingPredicate:preLogic];
NSLog(@"%@",logicArr);
//3.字符串比较运算符 BEGINSWITH,ENDSWITH,CONTAINS,LIKE,MATCHES
/*
BEGINSWITH '',ENDSWITH '',CONTAINS '', LIKE '', MATCHES '';
不区分大小写,可以加上[c](CASE INSENSITIVE);不区分重音符号,可以加上[d];既不区分大小写,也不区分重音符号,就加上[cd];
*/
NSString*testStr =@"jack";
NSPredicate*preStr = [NSPredicatepredicateWithFormat:@"SELF LIKE[cd] '?c*'"];
if([preStrevaluateWithObject:testStr]) {
NSLog(@"%@",testStr);
}
//4.集合运算符
/*
ANY,SOME:集合中任意一个元素满足条件,就返回YES.
ALL:集合中所有元素都满足条件,返回true
NONE:
IN: 等价于SQL语句中的IN运算符,只有当左边表达式或值出现在右边的结合中才返回yes.
*/
NSArray*filterArr = @[@"ab",@"abc"];
NSArray*allArr = @[@"a",@"ab",@"abc",@"ac"];
NSPredicate*preArr = [NSPredicatepredicateWithFormat:@"NOT (SELF IN (%@))",filterArr];
NSArray*result = [allArrfilteredArrayUsingPredicate:preArr];
NSLog(@"%@",result);
//5.直接量
/*
FALSE,NO
TRUE,YES
NULL,NIL
SELF
"string",'string':代表字符串
*/
//6.保留字(关键字)
/*
AND,OR,NOT,IN,ALL,SOME,NONE,LIKE,ANY,CASEINSENSITIVE,CI,MATCHES,CONTAINS,BEGINSWITH,ENDSWITH,BETWEEN,NULL,NIL,SELF,TRUE,YES,FALSE,NO,FIRST,LAST,SIZE,ANYKEY,SUBQUERY,CAST,TRUEPREDICATE,FALSEPREDICATE
建议这些关键字都用大写(理论上来说是不区分大小写的)
*/
//二:简单使用
// 例1:
YAOModel*yao = [YAOModelallocPersonWithName:@"yao"age:20sex:YaoPresonSexMale];
YAOModel*wang = [YAOModelallocPersonWithName:@"wang"age:18sex:YaoPresonSexFamale];
NSPredicate*preName = [NSPredicatepredicateWithFormat:@"(mName LIKE[c] 'y*') AND (mAge > 20)"];
BOOLjudgeYao = [preNameevaluateWithObject:yao];
BOOLjudgeWang = [preNameevaluateWithObject:wang];
NSString*testPhoneStr =@"13345678919";
judgeYao = [selfcheckPhoneNumber:testPhoneStr];
NSString*testSpecial =@"!{";
judgeYao = [selfcheckSpecialCharacter:testSpecial];//应该是YES,但是结果是NO,说明谓词还是没有我们想象中的那么好,没有正则匹配匹配的好,所以这个东西还是需要正则来匹配的
//2.在谓词中使用占位符参数
/*
%K: 动态传入属性名
%@: 动态设置属性值
除此之外,还可以在谓词表达式中使用动态改变的属性值,就像环境变量一样
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS $VALUE"];
上述表达式中,$VALUE是一个可以动态变化的值,它其实最后是在字典中的一个key,所以可以根据你的需要写不同的值,但是必须有$开头,随着程序改变$VALUE这个谓词表达式的比较条件就可以动态改变。
*/
NSArray*LastArr = @[[YAOModelallocPersonWithName:@"jack"age:20sex:YaoPresonSexFamale],[YAOModelallocPersonWithName:@"wang"age:22sex:YaoPresonSexFamale],[YAOModelallocPersonWithName:@"yao"age:22sex:YaoPresonSexMale]];
//1.创建一个property来存放属性名,value来存放属性值
NSString*property =@"mName";
NSString*value =@"jack";
//其实就是一个代替,property由%K在占位,value由%@在占位
NSPredicate*predict = [NSPredicatepredicateWithFormat:@"%K CONTAINS %@",property,value];
NSArray*newArr = [LastArrfilteredArrayUsingPredicate:predict];
//2.
NSPredicate*pred = [NSPredicatepredicateWithFormat:@"%K > $VALUE",@"mAge"];
NSPredicate*pred1= [predpredicateWithSubstitutionVariables:@{@"VALUE":@18}];
NSArray*newArr1= [LastArrfilteredArrayUsingPredicate:pred1];
}
//例2: 判断手机号是否正确输入
- (BOOL)checkPhoneNumber:(NSString*)phoneNumberStr {
NSString*regex =@"^[1][3-8]\\d{9}$";
NSPredicate*pre = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@",regex];
return[preevaluateWithObject:phoneNumberStr];
}
//例三:判断是否含有特殊字符
- (BOOL)checkSpecialCharacter:(NSString*)str {
//仿照判断手机号
NSString*regex =@"[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?]";
NSPredicate*pre = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@",regex];
return[preevaluateWithObject:str];
}
#pragma mark -- UITableViewDelegate UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
return1;
}
- (NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section {
returnmIsSearch?mSearchResultArray.count:mDataArray.count;
}
- (UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath {
staticNSString*cellId =@"searchCell";
UITableViewCell*cell = [tableViewdequeueReusableCellWithIdentifier:cellId];
if(!cell) {
cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellId];
}
cell.textLabel.text= mIsSearch?[mSearchResultArrayobjectAtIndex:indexPath.row]:[mDataArrayobjectAtIndex:indexPath.row];
returncell;
}
#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar*)searchBar {
}
- (void)searchBarTextDidEndEditing:(UISearchBar*)searchBar {
}
- (void)searchBar:(UISearchBar*)searchBartextDidChange:(NSString*)searchText {
[selffilterBySubStr:searchText];
}
- (void)searchBarSearchButtonClicked:(UISearchBar*)searchBar {
[selffilterBySubStr:searchBar.text];
[mTableViewreloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar*)searchBar __TVOS_PROHIBITED {
mIsSearch =NO;
[mTableViewreloadData];
}
- (void)searchBarResultsListButtonClicked:(UISearchBar*)searchBar NS_AVAILABLE_IOS(3_2) __TVOS_PROHIBITED {
}// called when search results button pressed
#pragma mark - private function
- (void)filterBySubStr:(NSString*)subStr {
mIsSearch =YES;
NSPredicate*pre = [NSPredicatepredicateWithFormat:@"SELF CONTAINS[c] %@",subStr];
mSearchResultArray = [mDataArrayfilteredArrayUsingPredicate:pre];
[mTableViewreloadData];
}
YaoModel:
[objc]view plaincopy
typedefNS_ENUM(NSInteger, YaoPresonSex) {
YaoPresonSexMale =0,
YaoPresonSexFamale
};
@interfaceYAOModel : NSObject
@property(nonatomic,copy)NSString*mName;
@property(nonatomic, assign) NSInteger mAge;
@property(nonatomic, assign) YaoPresonSex mSex;
+ (instancetype)allocPersonWithName:(NSString*)nameage:(NSInteger)agesex:(YaoPresonSex)sex;
[objc]view plaincopy
@implementationYAOModel
+ (instancetype)allocPersonWithName:(NSString*)nameage:(NSInteger)agesex:(YaoPresonSex)sex {
YAOModel*model = [[YAOModelalloc]init];
model.mName= name;
model.mAge= age;
model.mSex= sex;
returnmodel;
}
NSPredict使用
数组中有多个字典,字典中有name,code,extcode,jianpin等key,我们匹配的时候需要匹配name, code,extcode,jianpin这四个key,如下:
NSArray*resultArr = [NSArrayarray];
NSMutableArray*cacheResultArr = [NSMutableArrayarray];
NSString*property;
if(mResultCodeArr && mResultCodeArr.count >0) {
[mResultCodeArr removeAllObjects];
}
// name code extcode jianpin
NSArray*searchArr =@[@"name",@"code",@"extcode",@"jianpin"];
for(inti =0; i
property = searchArr[i];
NSPredicate*predict = [NSPredicate predicateWithFormat:@"%K CONTAINS %@",property,subStr];
resultArr = [mCodeArr filteredArrayUsingPredicate:predict];
for(NSString*contentStrinresultArr) {
[cacheResultArraddObject:contentStr];
}
}
//去重
if(cacheResultArr.count>0) {
for(inti =0; i
if(![mResultCodeArr containsObject:cacheResultArr[i]]) {
[mResultCodeArr addObject:cacheResultArr[i]];
}
}
}