您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS NSPredicate 使用教學:正則表達式、BETWEEN、IN 與 LIKE 過濾

編輯:iOS 開發綜合

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 開發中非常實用的工具。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved