NSPredicate 是 Cocoa 中常用的查詢與過濾工具,可用來過濾陣列、驗證字串,甚至搭配正則表達式。
NSString *regex = @"^[A-Za-z0-9]{9,15}$";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL isMatch = [pred evaluateWithObject:txtfldPhoneNumber.text];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == 'Herbie'"];
BOOL match = [predicate evaluateWithObject:car];
predicate = [NSPredicate predicateWithFormat:@"engine.horsepower > 150"];
NSArray *results = [cars filteredArrayUsingPredicate:predicate];
BETWEEN:判斷數值是否落在範圍內。
IN:判斷值是否屬於集合。
BEGINSWITH、ENDSWITH、CONTAINS:字串前綴、後綴與包含判斷。
LIKE:支援 * 與 ? 等萬用字元。
predicate = [NSPredicate predicateWithFormat:@"engine.horsepower BETWEEN { 50, 200 }"];
predicate = [NSPredicate predicateWithFormat:@"name IN { 'Herbie', 'Snugs', 'Badger' }"];
predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] 'HERB'"];
predicate = [NSPredicate predicateWithFormat:@"name LIKE[cd] '*er*'"];
附加符號 [c] 表示不區分大小寫,[d] 表示不區分發音字符,[cd] 則同時忽略兩者。使用 SELF 可對物件本身屬性進行匹配。
NSPredicate 的優勢在於語法直覺、可讀性高,也能與 Core Data、NSArray、NSSet 等 API 搭配,是 iOS 開發中非常實用的工具。