您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

NSPredicate 官方文件中文翻譯與重點整理

編輯:iOS 相關資訊

網路上對 NSPredicate 的講解多偏粗略,因此直接翻閱官方文件並翻譯整理如下,以加深理解(若有疏漏,歡迎指正)。

概覽

NSPredicate 類別用來定義「邏輯條件約束」,可用於從記憶體中的物件集合進行過濾搜尋。你可以用謂詞來描述邏輯條件,以過濾物件。雖然可以直接從 NSComparisonPredicate、NSCompoundPredicate、NSExpression 建立謂詞,但更常見的是透過 NSPredicate 的類方法解析格式字串來建立。

謂詞格式字串的例子:

  • 簡單比較:grade == "7" 或 firstName like "Shaffiq"
  • 不區分大小寫與音調的查找:name contains[cd] "itroen"
  • 邏輯運算:(firstName like "Mark") OR (lastName like "Adderley")
  • 區間謂詞(OS X 10.5 以後):date between {$YESTERDAY, $TOMORROW}

關係謂詞:

  • group.name like "work*"
  • ALL children.age > 12
  • ANY children.age > 12

運算謂詞:@sum.items.price < 1000。完整語法請參閱「謂詞編程指南」。

此外,你也可以建立含變數的謂詞,讓它在執行期替換成具體值。在 OS X 10.4 中,含變數的謂詞估算是一個兩步驟過程;10.5 以後則可用 evaluateWithObject:substitutionVariables: 一步完成。

常用類方法

1. predicateWithBlock:

+ (NSPredicate *)predicateWithBlock:(BOOL (^)(id evaluatedObject, NSDictionary *bindings))block;

建立並回傳一個以指定 block 進行評估的謂詞。block 帶有兩個參數:evaluatedObject(被評估的物件)與 bindings(用於替換變數的字典)。若計算結果為 true 則回傳 YES,否則 NO。

注意:OS X 10.6 起,Core Data 在記憶體與原子儲存中支援此方法,但 SQLite 儲存不支援。iOS 4.0 以後可用。

2. predicateWithFormat:

+ (NSPredicate *)predicateWithFormat:(NSString *)format, ...;

以給定的格式字串建立並回傳新謂詞。format 為格式字串,後接以逗號分隔的參數清單。iOS 3.0 以後可用。

3. predicateWithFormat:argumentArray:

+ (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat
                       argumentArray:(NSArray *)arguments;

把陣列中的值依序代入格式字串並解析,建立並回傳新謂詞。iOS 3.0 以後可用。

4. predicateWithFormat:arguments:

+ (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat arguments:(va_list)argList;

把參數清單中的值依序代入格式字串並解析。iOS 3.0 以後可用。

5. predicateWithValue:

+ (NSPredicate *)predicateWithValue:(BOOL)value;

建立並回傳一個直接評估給定值的謂詞。iOS 3.0 以後可用。

常用實例方法

1. evaluateWithObject:

- (BOOL)evaluateWithObject:(id)object;

回傳一個 BOOL 值,指示給定物件是否符合接收者的條件。符合回傳 YES,否則 NO。

2. evaluateWithObject:substitutionVariables:

- (BOOL)evaluateWithObject:(id)object substitutionVariables:(NSDictionary *)variables;

在用字典替換變數後,回傳物件是否符合條件。此方法的效果等同「先呼叫 predicateWithSubstitutionVariables:,再對回傳的謂詞呼叫 evaluateWithObject:」兩步驟,且在反覆評估不同變數時經過效能優化。

3. predicateFormat

- (NSString *)predicateFormat;

回傳接收者的格式字串。注意:此方法回傳的字串不保證與建立時完全相同,因此不能用來做持久化表示;若需持久化,應建立 NSPredicate 的 archive(NSPredicate 採用 NSCoding 協定)。

4. predicateWithSubstitutionVariables:

- (NSPredicate *)predicateWithSubstitutionVariables:(NSDictionary *)variables;

以字典中的值替換接收者的變數,回傳接收者的副本。原接收者不會被改變,因此可重複 reuse 任意次數的替換。

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