IOS開發之NSPredicate謂詞的用法,iosnspredicate謂詞
編程的人員不管是上過大學還是從培訓機構出來的或做背景、前端的都應該SQL語句有所瞭解,我們知道,在SQL語句當中 where 條件運算式可以對二維關係表的資料做條件式篩選.微軟的C# .net中也實現了功能能和SQL語句相媲美的技術,它就是List泛型集合的Lambda運算式,支援尋找、排序、比較、組合等.在java中雖然沒有在語言中整合對List對象的操作的實現,但是第三方開源庫同樣實現了這一功能.在IOS開發Cocoa架構中提供了一個功能強大的類NSPredicate,下面來討論一下它的強大之處在哪...
NSPredicate繼承自NSObject,它有兩個派生的子類
•NSComparisonPredicate
•NSCompoundPredicate (子類不是我們今天討論的對象,暫且瞭解一下就行)
說到謂詞,我們先來看一下謂詞的文法。
1.比較子
* >:大於
* <:小於
* >=:大於等於
* <=:小於等於
* =,==:等於
* !=,<>:不等於
2.邏輯運算子
*and /&&和
*or/||或
*not/!非
3.關係運算子
*ANY任意,SOME 一些
*ALL所有元素
*NONE沒有元素 等同於not any
*in包含
4.範圍運算子
* between 如,1 BETWEEN { 0 , 33 },或者$INPUT BETWEEN { $LOWER, $UPPER }。
* in包含
4.字串本身
*SELF 如:@“self==‘APPLEIOS’”
5.字串相關
*contain
*between
*endswith
6.like萬用字元
* like 如:@"name like[cd] '*ios*'"
@"name" like[cd] 'ios*'"
7.Regexmatches
*如:NSString *regex = @"^A.+e$"; //以A開頭,e結尾
@"name MATCHES %@",regex
8.數組操作
* array[index]:指定數組中特定索引處的元素。
*array[first]:制定第一個元素
*array[last]:制定最後一個元素
*array[size]:制定數組大小
下面我們再來看一下具體的案例:
建立一個項目,然後添加類products
Products.h
1 // 2 // Products.h 3 // NSPredicateTest 4 // 5 // Created by xuhongjiang on 15/10/27. 6 // Copyright (c) 2015年 xuhongjiang. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h>10 11 @interface Products : NSObject12 @property NSString *productName;13 @property NSInteger productCount;14 @property NSString *productImageUrl;15 +(id)initProductWithName:(NSString *) name withCount:(NSInteger) count withImage:(NSString *) imageurl;16 @end
Products.m
1 // 2 // Products.m 3 // NSPredicateTest 4 // 5 // Created by xuhongjiang on 15/10/27. 6 // Copyright (c) 2015年 xuhongjiang. All rights reserved. 7 // 8 9 #import "Products.h"10 11 @implementation Products12 +(id)initProductWithName:(NSString *)name withCount:(NSInteger)count withImage:(NSString *)imageurl13 {14 Products *sprducts=[[Products alloc] init];15 sprducts.productName=name;16 sprducts.productCount=count;17 sprducts.productImageUrl=imageurl;18 return sprducts;19 }20 -(NSString *)description21 {22 NSString *str=[NSString stringWithFormat:@"產品名稱:%@,數量:%ld,圖片:%@",_productName,_productCount,_productImageUrl];23 return str;24 }25 @end
測試方法:
1 // 2 // ViewController.m 3 // NSPredicateTest 4 // 5 // Created by xuhongjiang on 15/10/27. 6 // Copyright (c) 2015年 xuhongjiang. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 #import "Products.h" 11 12 @interface ViewController () 13 14 @end 15 16 @implementation ViewController 17 18 - (void)viewDidLoad { 19 [super viewDidLoad]; 20 [self mainTest]; 21 } 22 23 - (void)didReceiveMemoryWarning { 24 [super didReceiveMemoryWarning]; 25 } 26 27 -(void) mainTest 28 { 29 Products *p1=[Products initProductWithName:@"A蘋果sdasf" withCount:2 withImage:@"464.jpg"]; 30 Products *p2=[Products initProductWithName:@"fsdf橘子gag" withCount:53 withImage:@"fsdfas.jpg"]; 31 Products *p3=[Products initProductWithName:@"dfgdf香蕉" withCount:5 withImage:@"sfas.jpg"]; 32 Products *p4=[Products initProductWithName:@"三星" withCount:76 withImage:@"ggas.jpg"]; 33 Products *p5=[Products initProductWithName:@"華為dfsd" withCount:9 withImage:@"gasa.jpg"]; 34 Products *p6=[Products initProductWithName:@"微軟dhnnne" withCount:6 withImage:@"hshhh.jpg"]; 35 Products *p7=[Products initProductWithName:@"三星" withCount:6 withImage:@"hshhh.jpg"]; 36 Products *p8=[Products initProductWithName:@"15300250500" withCount:6 withImage:@"hshhh.jpg"]; 37 38 NSArray *sproducts=[NSArray arrayWithObjects:p1,p2,p3,p4,p5,p6,p7,nil]; 39 40 //數量小於9 定義謂詞 包含過濾條件 41 NSPredicate *prdicate=[NSPredicate predicateWithFormat:@"productCount<%d",9]; 42 //過濾結果返回新的數組 43 NSArray *newArray=[sproducts filteredArrayUsingPredicate:prdicate]; 44 for (Products *item in newArray) { 45 NSLog(@"newArray=%@",item.productName); 46 } 47 48 49 //數量大於9 並且productname等於“三星jfggg” 定義謂詞 包含過濾條件 50 prdicate=[NSPredicate predicateWithFormat:@"productName='三星' && productCount>9"]; 51 //過濾結果返回新的數組 52 newArray=[sproducts filteredArrayUsingPredicate:prdicate]; 53 for (Products *item in newArray) { 54 NSLog(@"newArray=%@",item.productName); 55 } 56 57 //in(包含) *注意 包含是全字匹配 58 prdicate = [NSPredicate predicateWithFormat:@"productName IN {'g','華為','三星'}||productCount IN {2,5}"]; 59 //過濾結果返回新的數組 60 newArray=[sproducts filteredArrayUsingPredicate:prdicate]; 61 for (Products *item in newArray) { 62 NSLog(@"newArray=%@",item.productName); 63 } 64 65 66 //productName以a開頭的 67 prdicate = [NSPredicate predicateWithFormat:@"productName BEGINSWITH 'A'"]; 68 //productName以ba結尾的 69 prdicate = [NSPredicate predicateWithFormat:@"productName ENDSWITH 'g'"]; 70 71 //name中包含字元a的 72 prdicate = [NSPredicate predicateWithFormat:@"productName CONTAINS 'a'"]; 73 74 //like 匹配任意多個字元 75 //productName中只要有s字元就滿足條件 76 prdicate = [NSPredicate predicateWithFormat:@"productName like '*s*'"]; 77 //?代表一個字元,下面的查詢條件是:name中第二個字元是s的 78 prdicate = [NSPredicate predicateWithFormat:@"productName like '?s*'"]; 79 80 newArray=[sproducts filteredArrayUsingPredicate:prdicate]; 81 for (Products *item in newArray) { 82 NSLog(@"newArray=%@",item.productName); 83 } 84 85 //Regex 驗證是否是手機號 86 BOOL isMobileNum=[self isMobileNumber:p8.productName]; 87 if(isMobileNum) 88 NSLog(@"是真確的手機號:%@",p8.productName); 89 90 } 91 92 93 - (BOOL)isMobileNumber:(NSString *)mobileNum 94 { 95 /** 96 * 手機號碼 97 * 移動:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188 98 * 聯通:130,131,132,152,155,156,185,186 99 * 電信:133,1349,153,180,189100 */101 NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";102 /**103 10 * 中國移動:China Mobile104 11 * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188105 12 */106 NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";107 /**108 15 * 中國聯通:China Unicom109 16 * 130,131,132,152,155,156,185,186110 17 */111 NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";112 /**113 20 * 中國電信:China Telecom114 21 * 133,1349,153,180,189115 22 */116 NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";117 /**118 25 * 大陸地區固話及小靈通119 26 * 區號:010,020,021,022,023,024,025,027,028,029120 27 * 號碼:七位或八位121 28 */122 // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";123 124 NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];125 NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];126 NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];127 NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];128 129 if (([regextestmobile evaluateWithObject:mobileNum] == YES)130 || ([regextestcm evaluateWithObject:mobileNum] == YES)131 || ([regextestct evaluateWithObject:mobileNum] == YES)132 || ([regextestcu evaluateWithObject:mobileNum] == YES))133 {134 if([regextestcm evaluateWithObject:mobileNum] == YES) {135 NSLog(@"中國移動");136 } else if([regextestct evaluateWithObject:mobileNum] == YES) {137 NSLog(@"聯通");138 } else if ([regextestcu evaluateWithObject:mobileNum] == YES) {139 NSLog(@"電信");140 } else {141 NSLog(@"Unknow");142 }143 144 return YES;145 }146 else147 {148 return NO;149 }150 }151 @end
1.查詢產品數量小於9的產品
這裡的代碼很簡單,第一步建立一個過濾器,用預留位置替換數量9,過濾器返回一個新的數組,之後遍曆數組,只取產品名稱。
//數量小於9 定義謂詞 包含過濾條件 NSPredicate *prdicate=[NSPredicate predicateWithFormat:@"productCount<%d",9]; //過濾結果返回新的數組 NSArray *newArray=[sproducts filteredArrayUsingPredicate:prdicate]; for (Products *item in newArray) { NSLog(@"newArray=%@",item.productName); }
2.查詢數量大於9 並且productname等於“三星jfggg”的產品
//數量大於9 並且productname等於“三星jfggg” 定義謂詞 包含過濾條件 prdicate=[NSPredicate predicateWithFormat:@"productName='三星' && productCount>9"]; //過濾結果返回新的數組 newArray=[sproducts filteredArrayUsingPredicate:prdicate];
3.in包含 (*注 包含是全字匹配)
prdicate = [NSPredicate predicateWithFormat:@"productName IN {'g','華為','三星'}||productCount IN {2,5}"]; //過濾結果返回新的數組 newArray=[sproducts filteredArrayUsingPredicate:prdicate];
4.字串相關處理
//productName以a開頭的 prdicate = [NSPredicate predicateWithFormat:@"productName BEGINSWITH 'A'"]; //productName以ba結尾的 prdicate = [NSPredicate predicateWithFormat:@"productName ENDSWITH 'g'"]; //name中包含字元a的 prdicate = [NSPredicate predicateWithFormat:@"productName CONTAINS 'a'"];
5.like萬用字元,用於模糊查詢
//like 匹配任意多個字元 //productName中只要有s字元就滿足條件 prdicate = [NSPredicate predicateWithFormat:@"productName like '*s*'"]; //?代表一個字元,下面的查詢條件是:name中第二個字元是s的 prdicate = [NSPredicate predicateWithFormat:@"productName like '?s*'"]; newArray=[sproducts filteredArrayUsingPredicate:prdicate];
6.Regex,例子是驗證是否是手機號
//Regex串 NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";//建立含有Regex的帥選器 NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];//篩選器的evaluateWithObject方法反向驗證是否手機號,返回bool值BOOL isPhoneNum=[regextestmobile evaluateWithObject:@"15300250500"] ;
關於謂詞的使用,我們只列舉了幾個常見的用法,它還有很多種靈活的用法,如對時間datetime的間隔篩選、謂詞變數 ”謂詞==$變數名“等,待有時間希望大家去研究。