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];