IOS開發之NSPredicate謂詞的用法


編程的人員不管是上過大學還是從培訓機構出來的或做后台的、前端的都應該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.正則表達式matches
     *如: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 : NSObject
12 @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 Products
12 +(id)initProductWithName:(NSString *)name withCount:(NSInteger)count withImage:(NSString *)imageurl
13 {
14     Products *sprducts=[[Products alloc] init];
15     sprducts.productName=name;
16     sprducts.productCount=count;
17     sprducts.productImageUrl=imageurl;
18     return sprducts;
19 }
20 -(NSString *)description
21 {
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     //正則表達式 驗證是否是手機號
 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,189
100      */
101     NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
102     /**
103      10         * 中國移動:China Mobile
104      11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
105      12         */
106     NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
107     /**
108      15         * 中國聯通:China Unicom
109      16         * 130,131,132,152,155,156,185,186
110      17         */
111     NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
112     /**
113      20         * 中國電信:China Telecom
114      21         * 133,1349,153,180,189
115      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,029
120      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     else
147     {
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.正則表達式,例子是驗證是否是手機號

//正則表達式串
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
//創建含有正則表達式的帥選器
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//篩選器的evaluateWithObject方法反向驗證是否手機號,返回bool值
BOOL isPhoneNum=[regextestmobile evaluateWithObject:@"15300250500"] ;

 

關於謂詞的使用,我們只列舉了幾個常見的用法,它還有很多種靈活的用法,如對時間datetime的間隔篩選、謂詞變量 ”謂詞==$變量名“等,待有時間希望大家去研究。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM