剛開始接觸這個(gè)類是在textfield中正則表達(dá)時(shí)驗(yàn)證輸入文本的狀態(tài)下,例子:
?NSString * pattern = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$";
?NSPredicate * pred=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
通過正則表達(dá)式判斷所輸入字符是否符合規(guī)范
1御吞、然而還是小看了這個(gè)類,過濾作用十分強(qiáng)大,有好多的關(guān)鍵字
舉個(gè)例子:
加入app中某一接口中有4張圖片师枣,而要求分成倆組,后臺(tái)會(huì)給你一個(gè)字段作為標(biāo)識(shí)進(jìn)行分組
模擬一下json解析下來數(shù)據(jù)創(chuàng)建個(gè)字典
NSDictionary *dic= @{
@"picture":@[
@{
@"groupId" : @"1",
@"picUrl" : @"app/pic1.jpg"
},
@{
@"groupId" : @"1",
@"picUrl" : @"app/pic2.jpg"
},
@{
@"groupId" : @"2",
@"picUrl" : @"app/pic3.jpg"
},
@{
@"groupId" : @"2",
@"picUrl" : @"app/pic4.jpg"
}
]
};
用數(shù)據(jù)時(shí)你會(huì)建立一個(gè)模型來接收數(shù)據(jù)信柿,模型就叫picModel吧
@property(nonatomic,strong)NSString *picUrl;
@property(nonatomic,strong)NSString *groupId;
我們創(chuàng)建一個(gè)可變數(shù)組把模型都存進(jìn)去mutableArr,這里有4個(gè)picModel
NSArray *dataArr=dic[@"picture"];
NSMutableArray *mutableArr=[[NSMutableArray alloc]init];
for (NSDictionary *dic in dataArr) {
picModel *pm=[[picModel alloc]init];
pm.picUrl=dic[@"picUrl"];
pm.groupId=dic[@"groupId"];
[mutableArr addObject:pm];
}
//這時(shí)打印的數(shù)組元素個(gè)數(shù)是4個(gè)
NSLog(@"%zd",mutableArr.count);
創(chuàng)建一個(gè)謂詞規(guī)則 就是groupId為1的過濾出來因?yàn)?是NSString類型所以得加引號(hào)那么寫
NSPredicate *preGroup1=[NSPredicate predicateWithFormat:@"self.groupId='1'"];
NSPredicate *preGroup2=[NSPredicate predicateWithFormat:@"self.groupId='2'"];
重寫一下description
-(NSString *)description{
[super description];
return [NSString stringWithFormat:@"ID=%@,URL=%@",self.groupId,self.picUrl];
}
運(yùn)用規(guī)則得出對(duì)應(yīng)數(shù)組?
NSArray *group1=[mutableArr filteredArrayUsingPredicate:preGroup1];
NSArray *group2=[mutableArr filteredArrayUsingPredicate:preGroup2];
NSLog(@"group1=%@",group1);
NSLog(@"group2=%@",group2);
打印出來看結(jié)果發(fā)現(xiàn)被分成倆組了
group1=(
"ID=1,URL=app/pic1.jpg",
"ID=1,URL=app/pic2.jpg"
)
group2=(
"ID=2,URL=app/pic3.jpg",
"ID=2,URL=app/pic4.jpg"
)
NSPredicate還有很多關(guān)鍵字 像contains,like等有些實(shí)際需求會(huì)用到