首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS Core Data 謂詞組合:使用 NSCompoundPredicate 實現 AND/OR 邏輯

     編輯:程式設計綜合問答

問題背景

需構建查詢謂詞:(category 包含 cat0 OR cat1 OR cat2) AND (mark == 1)。

構建步驟

NSMutableArray *orPredicates = [NSMutableArray array];
if (cat0str.length) [orPredicates addObject:[NSPredicate predicateWithFormat:@"question.category CONTAINS[c] %@", cat0str]];
if (cat1str.length) [orPredicates addObject:[NSPredicate predicateWithFormat:@"question.category CONTAINS[c] %@", cat1str]];
if (cat2str.length) [orPredicates addObject:[NSPredicate predicateWithFormat:@"question.category CONTAINS[c] %@", cat2str]];

NSPredicate *compoundOr = [NSCompoundPredicate orPredicateWithSubpredicates:orPredicates];
NSPredicate *markPred = [NSPredicate predicateWithFormat:@"question.mark == 1"];

// 組合 AND
NSPredicate *finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[compoundOr, markPred]];

[fetchRequest setPredicate:finalPredicate];

現代語法(Swift 風格)

NSPredicate *finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[compoundOr, markPred]];

關鍵類

  • NSCompoundPredicate:提供 andPredicateWithSubpredicates:、orPredicateWithSubpredicates:、notPredicateWithSubpredicate:
  • 子謂詞數組順序不影響邏輯結果
  • 可嵌套構建複雜邏輯:AND(OR(A,B), NOT(C))
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved