系統(tǒng)提供了NSPredicate這個(gè)類給我們進(jìn)行一些匹配切油、篩選操作蝙斜,非常方便。在沒有用這個(gè)類時(shí)澎胡,我們要獲取兩個(gè)數(shù)組中某些特定的元素時(shí)孕荠,需要寫代碼一一對(duì)比,但是使用了這個(gè)類攻谁,只需要三四行代碼就夠了稚伍。
先演示一個(gè)謂詞在在類中使用
KKMonthModel.h文件
@interface KKMonthModel : KKBaseModel
/**年份*/
@property(nonatomic,copy)NSString *date_year;
/**月份*/
@property(nonatomic,copy)NSString *date_month;
/**日*/
@property(nonatomic,copy)NSString *date_day;
/**預(yù)約數(shù)量*/
@property(nonatomic,copy)NSString *appoint_num;
/**上門數(shù)量*/
@property(nonatomic,copy)NSString *receive_num;
@end
KKMonthModle.m文件(取開發(fā)中的部分代碼示例)
if (models.count>0) {
for (KKMonthModel *monthModel in models) {
NSPredicate *pre=[NSPredicate predicateWithFormat:@"year==%ld&& month==%ld&& day==%ld",monthModel.date_year.integerValue,monthModel.date_month.integerValue,monthModel.date_day.integerValue];
NSArray *preArray=[headerModel.calendarItemArray filteredArrayUsingPredicate:pre];
if (preArray.count>0) {
KKCalendarModel *model=[preArray lastObject];
model.monthModel=monthModel;
}
}
謂詞主要實(shí)現(xiàn)對(duì)數(shù)組的篩選,數(shù)組里面可是字典巢株,當(dāng)然也可以是數(shù)組槐瑞。下面讓我給大家講講謂詞中常見的使用方法和場(chǎng)景
謂詞的使用使用方法
(1)比較運(yùn)算符
/**比較運(yùn)算符
* >:大于
* <:小于
* >=:大于等于
* <=:小于等于
* =,==:等于
* !=,<>:不等于
* BEGINSWITH:檢查某個(gè)字符串是否以指定的字符串開頭(如判斷字符串是否以a開頭:BEGINSWITH 'a')
* ENDSWITH:檢查某個(gè)字符串是否以指定的字符串結(jié)尾
* CONTAINS:檢查某個(gè)字符串是否包含指定的字符串
* LIKE:檢查某個(gè)字符串是否匹配指定的字符串模板熙涤。其之后可以跟?代表一個(gè)字符和*代表任意多個(gè)字符兩個(gè)通配符阁苞。比如"name LIKE '*ac*'"困檩,這表示name的值中包含ac則返回YES;"name LIKE '?ac*'"那槽,表示name的第2悼沿、3個(gè)字符為ac時(shí)返回YES。
*MATCHES:檢查某個(gè)字符串是否匹配指定的正則表達(dá)式骚灸。雖然正則表達(dá)式的執(zhí)行效率是最低的糟趾,但其功能是最強(qiáng)大的,也是我們最常用的甚牲。
// 例子:年齡屬性大于3歲,注意:鍵路徑不能用單引號(hào)引起來(lái)义郑,否則會(huì)報(bào)錯(cuò)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 3"];
(2)邏輯運(yùn)算符
/**邏輯運(yùn)算符
* and/&&:與
* or/||:或
* not/!:非
**/
// 例子:年齡大于三歲或名字叫“zhang1”的,注意:字符串的值需要用單引號(hào)引起來(lái)丈钙,否則會(huì)報(bào)錯(cuò)非驮,錯(cuò)誤信息是:this class is not key value coding-compliant for the key zhang1.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 3 || name = 'zhang1'"];
(3)關(guān)系運(yùn)算符
/**關(guān)系操作
* ANY,SOME:指定下列表達(dá)式中的任意元素雏赦。比如劫笙,ANY children.age < 18。
* ALL:指定下列表達(dá)式中的所有元素星岗。比如填大,ALL children.age < 18。
* NONE:指定下列表達(dá)式中沒有的元素俏橘。比如允华,NONE children.age < 18。它在邏輯上等于NOT (ANY ...)寥掐。
* IN:等于SQL的IN操作例获,左邊的表達(dá)必須出現(xiàn)在右邊指定的集合中。比如曹仗,name IN { 'Ben', 'Melissa', 'Nick' }榨汤。
**/
// 例子:in關(guān)鍵字:左邊的關(guān)鍵字里必須包含右邊的集合的元素
NSPredicate *predicate = [NSPredicate predicateWithFormat:@" name in {'zhang1','zhang4'}"];
謂詞的使用場(chǎng)景
(1)謂詞對(duì)對(duì)象數(shù)組的操作
#import <Foundation/Foundation.h>
@interface Products : NSObject
@property NSString *productName;
@property NSInteger productCount;
@property NSString *productImageUrl;
+(id)initProductWithName:(NSString *) name withCount:(NSInteger) count withImage:(NSString *) imageurl;
@end
.m文件中的使用
#import "ViewController.h"
#import "Products.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self mainTest];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void) mainTest
{
Products *p1=[Products initProductWithName:@"A蘋果sdasf" withCount:2 withImage:@"464.jpg"];
Products *p2=[Products initProductWithName:@"fsdf橘子gag" withCount:53 withImage:@"fsdfas.jpg"];
Products *p3=[Products initProductWithName:@"dfgdf香蕉" withCount:5 withImage:@"sfas.jpg"];
Products *p4=[Products initProductWithName:@"三星" withCount:76 withImage:@"ggas.jpg"];
Products *p5=[Products initProductWithName:@"華為dfsd" withCount:9 withImage:@"gasa.jpg"];
Products *p6=[Products initProductWithName:@"微軟dhnnne" withCount:6 withImage:@"hshhh.jpg"];
Products *p7=[Products initProductWithName:@"三星" withCount:6 withImage:@"hshhh.jpg"];
Products *p8=[Products initProductWithName:@"15300250500" withCount:6 withImage:@"hshhh.jpg"];
NSArray *sproducts=[NSArray arrayWithObjects:p1,p2,p3,p4,p5,p6,p7,nil];
//數(shù)量小于9 定義謂詞 包含過(guò)濾條件
NSPredicate *prdicate=[NSPredicate predicateWithFormat:@"productCount<%d",9];
//過(guò)濾結(jié)果返回新的數(shù)組
NSArray *newArray=[sproducts filteredArrayUsingPredicate:prdicate];
for (Products *item in newArray) {
NSLog(@"newArray=%@",item.productName);
}
//數(shù)量大于9 并且productname等于“三星jfggg” 定義謂詞 包含過(guò)濾條件
prdicate=[NSPredicate predicateWithFormat:@"productName='三星' && productCount>9"];
//過(guò)濾結(jié)果返回新的數(shù)組
newArray=[sproducts filteredArrayUsingPredicate:prdicate];
for (Products *item in newArray) {
NSLog(@"newArray=%@",item.productName);
}
//in(包含) *注意 包含是全字匹配
prdicate = [NSPredicate predicateWithFormat:@"productName IN {'g','華為','三星'}||productCount IN {2,5}"];
//過(guò)濾結(jié)果返回新的數(shù)組
newArray=[sproducts filteredArrayUsingPredicate:prdicate];
for (Products *item in newArray) {
NSLog(@"newArray=%@",item.productName);
}
//productName以a開頭的
prdicate = [NSPredicate predicateWithFormat:@"productName BEGINSWITH 'A'"];
//productName以ba結(jié)尾的
prdicate = [NSPredicate predicateWithFormat:@"productName ENDSWITH 'g'"];
//name中包含字符a的
prdicate = [NSPredicate predicateWithFormat:@"productName CONTAINS 'a'"];
//like 匹配任意多個(gè)字符
//productName中只要有s字符就滿足條件
prdicate = [NSPredicate predicateWithFormat:@"productName like '*s*'"];
//?代表一個(gè)字符,下面的查詢條件是:name中第二個(gè)字符是s的
prdicate = [NSPredicate predicateWithFormat:@"productName like '?s*'"];
newArray=[sproducts filteredArrayUsingPredicate:prdicate];
for (Products *item in newArray) {
NSLog(@"newArray=%@",item.productName);
}
//正則表達(dá)式 驗(yàn)證是否是手機(jī)號(hào)
BOOL isMobileNum=[self isMobileNumber:p8.productName];
if(isMobileNum)
NSLog(@"是真確的手機(jī)號(hào):%@",p8.productName);
}
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
/**
* 手機(jī)號(hào)碼
* 移動(dòng):134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
* 聯(lián)通:130,131,132,152,155,156,185,186
* 電信:133,1349,153,180,189
*/
NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
/**
10 * 中國(guó)移動(dòng):China Mobile
11 * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
12 */
NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
/**
15 * 中國(guó)聯(lián)通:China Unicom
16 * 130,131,132,152,155,156,185,186
17 */
NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
/**
20 * 中國(guó)電信:China Telecom
21 * 133,1349,153,180,189
22 */
NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
/**
25 * 大陸地區(qū)固話及小靈通
26 * 區(qū)號(hào):010,020,021,022,023,024,025,027,028,029
27 * 號(hào)碼:七位或八位
28 */
// NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
if (([regextestmobile evaluateWithObject:mobileNum] == YES)
|| ([regextestcm evaluateWithObject:mobileNum] == YES)
|| ([regextestct evaluateWithObject:mobileNum] == YES)
|| ([regextestcu evaluateWithObject:mobileNum] == YES))
{
if([regextestcm evaluateWithObject:mobileNum] == YES) {
NSLog(@"中國(guó)移動(dòng)");
} else if([regextestct evaluateWithObject:mobileNum] == YES) {
NSLog(@"聯(lián)通");
} else if ([regextestcu evaluateWithObject:mobileNum] == YES) {
NSLog(@"電信");
} else {
NSLog(@"Unknow");
}
return YES;
}
else
{
return NO;
}
}
@end
(2)謂詞對(duì)字典數(shù)組的操作
dataArray = [[NSMutableArray alloc] init];
NSDictionary * dataDic1 = @{@"image":[UIImage imageNamed:@"photo1.jpg"], @"content":@"I am a boy",@"publisher":@"趣玩高球", @"privateNum":@"122",@"lookNum":@"56"};
NSDictionary * dataDic2 = @{@"image":[UIImage imageNamed:@"photo2.jpg"], @"content":@"昨天中午有個(gè)男同事外出怎茫,沒把手機(jī)帶走收壕。他老婆不停地打電話來(lái)。午睡的女同事被吵煩了轨蛤,拿過(guò)手機(jī)大吼:我們?cè)谒X,你煩不煩蜜宪!結(jié)果,那位男同事今天到現(xiàn)在都沒來(lái)上班祥山!",@"publisher":@"趣玩高球", @"privateNum":@"122",@"lookNum":@"56"};
NSDictionary * dataDic3 = @{@"image":[UIImage imageNamed:@"photo3.jpg"], @"content":@"yesterday,my mom buy a apple圃验!",@"publisher":@"趣玩高球", @"privateNum":@"122",@"lookNum":@"56"};
NSDictionary * dataDic4 = @{@"image":[UIImage imageNamed:@"photo4.jpg"], @"content":@"昨天中午有個(gè)男同事外出,沒把手機(jī)帶走缝呕。他老婆不停地打電話來(lái)澳窑。午睡的女同事被吵煩了斧散,拿過(guò)手機(jī)大吼:我們?cè)谒X,你煩不煩!結(jié)果摊聋,那位男同事今天到現(xiàn)在都沒來(lái)上班鸡捐!",@"publisher":@"趣玩高球", @"privateNum":@"122",@"lookNum":@"56"};
[dataArray addObject:dataDic1];
[dataArray addObject:dataDic2];
[dataArray addObject:dataDic3];
[dataArray addObject:dataDic4];
這里是過(guò)濾KEY為@“content”的值為輸入框的值來(lái)搜索包含有這個(gè)輸入框輸入的文字的字典。
NSString * searchString = [lifeSearchController.searchBar text];
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"%K CONTAINS[c] %@",@"content",searchString];
if (searchListArray != nil) {
[searchListArray removeAllObjects];
}
//過(guò)濾數(shù)據(jù)
searchListArray = [NSMutableArray arrayWithArray:[dataArray filteredArrayUsingPredicate:predicate]];
NSLog(@"return****** %@",searchListArray);
//刷新表格
[headTableView reloadData];