NSPredicate簡單介紹,nspredicate

來源:互聯網
上載者:User

NSPredicate簡單介紹,nspredicate
NSPredicate中主要的幾種運算方式

1.比較子 > 、< 、== 、 >= 、<= 、 !=
例:@"number >= 99"

2.邏輯運算子:AND、OR、NOT 這幾個運算子計算並、或、非的結果。

3.範圍運算子:IN 、BETWEEN
例:@"number BETWEEN {1,5}"
@"address IN {'shanghai','nanjing'}"

4.字串本身:SELF
例:@"SELF == 'APPLE'"

5.字串相關:BEGINSWITH、ENDSWITH、CONTAINS
例: @"name CONTAIN[cd] 'ang'" //包含某個字串
@"name BEGINSWITH[c] 'sh'" //以某個字串開頭
@"name ENDSWITH[d] 'ang'" //以某個字串結束
注:[c]不區分大小寫 , [d]不區分發音符號即沒有重音符號 , [cd]既不區分大小寫,也不區分發音符號。

6.萬用字元:LIKE
例:@"name LIKE[cd] '*er*'" //*代表萬用字元,Like也接受[cd].
@"name LIKE[cd] '???er*'"

7.Regex:MATCHES
例:NSString *regex = @"^A.+e$"; //以A開頭,e結尾
@"name MATCHES %@",regex

用NSPredicate篩選兩個數組的差異

NSArray* array = @[@"aa",@"bb"];NSArray* array2 = @[@"aa",@"bb",@"cc",@"dd"];NSPredicate* thePredicate = [NSPredicate predicateWithFormat:@"NOT(SELF in %@)",array];NSArray* arr3 = [array2 filteredArrayUsingPredicate:thePredicate];NSLog(@"%@",arr3);

上面的代碼輸出結果 arr3={@"cc" ,@"dd"}

 

用NSPredicate篩選數組

NSString *regex = @"^A.+e$";//以A 開頭,以e 結尾的字元。NSPredicate *pre= [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];if([pre evaluateWithObject: @"Apple"]){

    NSLog(@"YES");

}else{

   NSLog(@"NO");

}

 

關於NSPredicate的其他說明和注意事項,以及技巧

動態屬性名稱

NSPredicate *p = [NSPredicate predicateWithFormat:@"name = %@", @"name1"];

顯然代碼沒有任何問題,但是這個不是最好的寫法我建議如下寫法:

NSPredicate *preTemplate = [NSPredicate predicateWithFormat:@"name==$NAME"];

NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:

@"name1", @"NAME",nil];

NSPredicate *pre=[preTemplate predicateWithSubstitutionVariables: dic];

這樣看上去可能會讓代碼邏輯更清晰。

當過濾條件欄位都是動態時候
NSString *key = @"name";     NSString *value = @"name1";      NSPredicate *p = [NSPredicate predicateWithFormat:@"%@ = %@", key, value];

然後當你執行到第三行的時候代碼就會報錯!

邏輯上沒錯誤啊!!!為什麼會出錯呢?
NSPredicate要自動添加引號,所以最後得到的格式應該是@"'name' = 'name1'"。明顯不對。要做的就是:

NSPredicate *p = [NSPredicate predicateWithFormat:@"%K = %@", key, value];

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.