
本文為投稿文章,作者:sunny_zl
蘋果官方對 NSPredicate 的定義是:
The NSPredicate class is used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.
翻譯過來就是:這個類用於定義邏輯條件,約束一次查詢(fetch)或一次內存中的過濾。
說得再直白一點——它就是一個過濾器,它把條件寫成表達式,不符合條件的元素統統被剔除,同時也就能用來描述 Core Data 持久層的檢索條件。
學任何一門語言都得從語法開始,否則很難把邏輯理順。這一節只談語法本身。
使用謂詞時必須提供一個謂詞表達式,而這個表達式的求值結果必須是 BOOL。表達式由表達式本身、運算符和值三部分構成。
=、==:判斷兩側表達式是否相等。注意在謂詞裡 = 和 == 含義完全相同,都表示比較,不存在賦值的說法。NSNumber *testNumber = @123;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF = 123"];
if ([predicate evaluateWithObject:testNumber]) {
NSLog(@"testString:%@", testNumber);
}
輸出:
2016-01-07 11:12:27.281 PredicteDemo[4130:80412] testString:123
>=、=>:左側值大於或等於右側值<=、=<:左側值小於或等於右側值>:左側值大於右側值<:左側值小於右側值!=、<>:兩側表達式不相等BETWEEN:格式固定為 表達式 BETWEEN {下限, 上限},要求值大於等於下限且小於等於上限NSNumber *testNumber = @123;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BETWEEN {100, 200}"];
if ([predicate evaluateWithObject:testNumber]) {
NSLog(@"testString:%@", testNumber);
} else {
NSLog(@"不符合條件");
}
輸出:
2016-01-07 11:20:39.921 PredicteDemo[4366:85408] testString:123
AND、&&:邏輯與,兩邊都為 YES 時結果才是 YESNSArray *testArray = @[@1, @2, @3, @4, @5, @6]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF > 2 && SELF < 5"]; NSArray *filterArray = [testArray filteredArrayUsingPredicate:predicate]; NSLog(@"filterArray:%@", filterArray);
輸出:
2016-01-07 11:27:01.885 PredicteDemo[4531:89537] filterArray:( 3, 4 )
OR、||:邏輯或,任意一邊為 YES 結果即為 YESNOT、!:邏輯非,對表達式取反BEGINSWITH:判斷字符串是否以指定內容開頭,例如 BEGINSWITH 'a'ENDSWITH:判斷字符串是否以指定內容結尾CONTAINS:判斷字符串是否包含指定內容LIKE:匹配字符串模板,? 匹配單個字符,* 匹配任意多個字符。例如 name LIKE '*ac*' 表示 name 中含有 ac 即返回 YES;name LIKE '?ac*' 表示第 2、3 個字符為 ac 時返回 YESMATCHES:匹配指定的正則表達式。效率最低但表達能力最強,實戰中最常用注意:字符串比較默認區分大小寫與重音符號,café 和 cafe 不等價,Cafe 和 cafe 也不等價。若希望忽略差異,可在運算符後追加選項:[c] 表示不區分大小寫,[d] 表示不區分重音符號。寫成 name LIKE[cd] 'cafe',那麼不論 name 是 cafe、Cafe 還是 café,結果都會是 YES。
ANY、SOME:集合中任意一個元素滿足條件即返回 YESALL:集合中所有元素都滿足條件才返回 YESNONE:集合中沒有任何元素滿足條件才返回 YES。例如 NONE person.age < 18 表示當集合內所有人的 age 都大於等於 18 時返回 YESIN:等價於 SQL 的 IN,只有左側的值出現在右側集合中才返回 YESNSArray *filterArray = @[@"ab", @"abc"]; NSArray *array = @[@"a", @"ab", @"abc", @"abcd"]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)", filterArray]; NSLog(@"%@", [array filteredArrayUsingPredicate:predicate]);
這段代碼的作用是從 array 中剔除 filterArray 已有的元素,輸出:
2016-01-07 13:17:43.669 PredicteDemo[6701:136206] ( a, abcd )
array[index]:取數組中指定索引處的元素array[FIRST]:取第一個元素array[LAST]:取最後一個元素array[SIZE]:取元素個數謂詞表達式中可以直接寫入以下字面量:
FALSE、NO:邏輯假TRUE、YES:邏輯真NULL、NIL:空值SELF:正在被判斷的對象自身"string" 或 'string':字符串{'one', 'two', 'three'}0x 開頭0o 開頭0b 開頭以下單詞均為保留字,大小寫不敏感:
AND、OR、IN、NOT、ALL、ANY、SOME、NONE、LIKE、CASEINSENSITIVE、CI、MATCHES、CONTAINS、BEGINSWITH、ENDSWITH、BETWEEN、NULL、NIL、SELF、TRUE、YES、FALSE、NO、FIRST、LAST、SIZE、ANYKEY、SUBQUERY、CAST、TRUEPREDICATE、FALSEPREDICATE
雖然大小寫都可以,但習慣上仍建議統一寫大寫,可讀性更好。
最常用的定義方式:
NSPredicate *predicate = [NSPredicate predicateWithFormat:];
先準備一個模型,後面的例子都會用到:
ZLPersonModel.h
#import
typedef NS_ENUM(NSInteger, ZLPersonSex) {
ZLPersonSexMale = 0,
ZLPersonSexFamale
};
@interface ZLPersonModel : NSObject
/** NSString 姓名 */
@property (nonatomic, copy) NSString *name;
/** NSUInteger 年齡 */
@property (nonatomic, assign) NSUInteger age;
/** ZLPersonSex 性別 */
@property (nonatomic, assign) ZLPersonSex sex;
+ (instancetype)personWithName:(NSString *)name age:(NSUInteger)age sex:(ZLPersonSex)sex;
@end
例一:最基礎的用法
ZLPersonModel *sunnyzl = [ZLPersonModel personWithName:@"sunnyzl" age:29 sex:ZLPersonSexMale]; ZLPersonModel *jack = [ZLPersonModel personWithName:@"jack" age:22 sex:ZLPersonSexMale]; // 1. 判斷姓名是否以 s 開頭 NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"name LIKE 's*'"]; // 輸出:sunnyzl:1, jack:0 NSLog(@"sunnyzl:%d, jack:%d", [pred1 evaluateWithObject:sunnyzl], [pred1 evaluateWithObject:jack]); // 2. 判斷年齡是否大於 25 NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"age > 25"]; // 輸出:sunnyzl 的年齡是否大於 25:1,jack 的年齡是否大於 25:0 NSLog(@"sunnyzl的年齡是否大於25:%d, jack的年齡是否大於25:%d", [pred2 evaluateWithObject:sunnyzl], [pred2 evaluateWithObject:jack]);
evaluateWithObject: 返回一個 BOOL,符合條件返回 YES,否則返回 NO。別小看這個能力,過去做手機號、郵編校驗,很多人習慣用 John Engelhart 的 RegexKitLite,但要導入 libicucore.dylib(Xcode 7 之後是 libicucore.tbd),而且因為它是 MRR 代碼還得額外加上 -fno-objc-arc 編譯標誌,折騰一圈才能用。換成謂詞,同樣簡潔的代碼就能搞定。
例二:校驗手機號
- (BOOL)checkPhoneNumber:(NSString *)phoneNumber {
NSString *regex = @"^[1][3-8]\\d{9}$";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
return [pred evaluateWithObject:phoneNumber];
}
例三:謂詞跑正則的坑
本意是檢測字符串中是否含有特殊字符:
- (BOOL)checkSpecialCharacter:(NSString *)string {
NSString *regex = @"[`~!@#$^&*()=|{}'-:;',\\[\\].<>/?~!@#¥……&*()——|{}【】';:""''。,、?]";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
return [pred evaluateWithObject:string];
}
期望是命中任意特殊字符就返回 YES,但實際表現並不如預期:
NSString *testString = @"!"; NSLog(@"是否含有特殊字符:%d", [self checkSpecialCharacter:testString]); // 輸出:是否含有特殊字符:1
看上去沒問題。換個值試試:
NSString *testString = @"!~"; NSLog(@"%d", [self checkSpecialCharacter:testString]); // 輸出:是否含有特殊字符:0
再換:
NSString *testString = @"abc!~d"; NSLog(@"%d", [self checkSpecialCharacter:testString]); // 輸出:是否含有特殊字符:0
結果與預期完全相反。原因在於匹配機制不同:用 NSRegularExpression 時,每匹配到一個結果就會記錄位置,然後從該位置繼續往下找;而 NSPredicate 不會做這種自動遞進,它實際上把表達式當成了 ^表達式$ 的全串匹配來處理。
結論很明確:只有正則本身寫成 ^...$ 形式時,才適合交給謂詞;其餘場景請老老實實用 NSRegularExpression。
當然,不能因為這一點瑕疵就否定它。除了正則匹配這個特例,NSPredicate 帶來的便利遠大於它的短板。
這是必須掌握的重點,也是謂詞真正強大的地方。
謂詞本身就代表一個邏輯條件,求值結果永遠是 BOOL。用它過濾集合時,系統會自動遍歷元素、逐個求值,只有返回 YES 的元素才會被保留,最後重新組合成一個新集合返回。
這個思路和 tableView 索引裡常見的這段代碼很像:
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [self.cityGroup valueForKey:@"title"];
}
其中 [self.cityGroup valueForKey:@"title"] 就是遍歷所有 title 並組裝成新數組。
各容器類提供的過濾接口:
NSArray:- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate;NSMutableArray:- (void)filterUsingPredicate:(NSPredicate *)predicate; 直接剔除不符合條件的元素NSSet:- (NSSet *)filteredSetUsingPredicate:(NSPredicate *)predicate;NSMutableSet:- (void)filterUsingPredicate:(NSPredicate *)predicate NS_AVAILABLE(10_5, 3_0); 作用同上也就是說:過濾不可變集合時返回一個新集合,過濾可變集合時沒有返回值,而是原地刪除不符合條件的元素。
例一:
NSMutableArray *arrayM = [@[@20, @40, @50, @30, @60, @70] mutableCopy];
// 過濾大於 50 的值
NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF > 50"];
[arrayM filterUsingPredicate:pred1];
NSLog(@"arrayM:%@", arrayM);
NSArray *array = @[[ZLPersonModel personWithName:@"Jack" age:20 sex:ZLPersonSexMale],
[ZLPersonModel personWithName:@"Rose" age:22 sex:ZLPersonSexFamale],
[ZLPersonModel personWithName:@"Jackson" age:30 sex:ZLPersonSexMale],
[ZLPersonModel personWithName:@"Johnson" age:35 sex:ZLPersonSexMale]];
// 取出姓名包含 'son' 的元素
NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"name CONTAINS 'son'"];
NSArray *newArray = [array filteredArrayUsingPredicate:pred2];
NSLog(@"%@", newArray);
輸出:
2016-01-07 16:50:09.510 PredicteDemo[13660:293822] arrayM:( 60, 70 ) 2016-01-07 16:50:09.511 PredicteDemo[13660:293822] ( "[name = Jackson, age = 30, sex = 0]", "[name = Johnson, age = 35, sex = 0]" )
如果不用謂詞,同樣的需求大概要寫一大坨 if...else 加循環。
例二:求差集
NSArray *filterArray = @[@"ab", @"abc"]; NSArray *array = @[@"a", @"ab", @"abc", @"abcd"]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)", filterArray]; NSLog(@"%@", [array filteredArrayUsingPredicate:predicate]);
輸出:
2016-01-07 13:17:43.669 PredicteDemo[6701:136206] ( a, abcd )
前面的例子裡謂詞都是寫死的,但實際開發中條件往往是變量。這就需要兩個占位符:
%K:動態傳入屬性名%@:動態傳入屬性值一個管變量名,一個管變量值。
除此之外,還可以在表達式中使用運行時可變的值,類似環境變量:
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS $VALUE"];
這裡的 $VALUE 對應字典中的一個 key,必須以 $ 開頭。程序運行過程中改變這個值,謂詞的比較條件就跟著變。
例一:
NSArray *array = @[[ZLPersonModel personWithName:@"Jack" age:20 sex:ZLPersonSexMale],
[ZLPersonModel personWithName:@"Rose" age:22 sex:ZLPersonSexFamale],
[ZLPersonModel personWithName:@"Jackson" age:30 sex:ZLPersonSexMale],
[ZLPersonModel personWithName:@"Johnson" age:35 sex:ZLPersonSexMale]];
// 屬性名與屬性值都做成變量
NSString *property = @"name";
NSString *value = @"Jack";
// 取出 name 中包含 Jack 的元素
NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K CONTAINS %@", property, value];
NSArray *newArray = [array filteredArrayUsingPredicate:pred];
NSLog(@"newArray:%@", newArray);
// 使用 $VALUE 占位符,比較 age
NSPredicate *predTemp = [NSPredicate predicateWithFormat:@"%K > $VALUE", @"age"];
// 第一次代入 25
NSPredicate *pred1 = [predTemp predicateWithSubstitutionVariables:@{@"VALUE": @25}];
NSArray *newArray1 = [array filteredArrayUsingPredicate:pred1];
NSLog(@"newArray1:%@", newArray1);
// 第二次代入 32
NSPredicate *pred2 = [predTemp predicateWithSubstitutionVariables:@{@"VALUE": @32}];
NSArray *newArray2 = [array filteredArrayUsingPredicate:pred2];
NSLog(@"newArray2:%@", newArray2);
輸出:
2016-01-07 17:28:02.062 PredicteDemo[14542:309494] newArray:( "[name = Jack, age = 20, sex = 0]", "[name = Jackson, age = 30, sex = 0]" ) 2016-01-07 17:28:02.063 PredicteDemo[14542:309494] newArray1:( "[name = Jackson, age = 30, sex = 0]", "[name = Johnson, age = 35, sex = 0]" ) 2016-01-07 17:28:02.063 PredicteDemo[14542:309494] newArray2:( "[name = Johnson, age = 35, sex = 0]" )
這個例子把 %K 與 $VALUE 的含義都演示清楚了:前者讓屬性名可配置,後者讓同一份謂詞能被反覆代入不同條件使用。
以上就是 NSPredicate 的全部要點。本人水平有限,如有更好的建議歡迎聯繫交流。