2010-10-17 80 views
10

我需要用許多數據創建一個NSPredicate。例如,在SQL我會做類似如下:構建複雜NSCompoundPredicate的最佳方法是什麼?

SELECT * 
    FROM TRANSACTIONS 
    WHERE CATEGORY IN (categoryList) 
    AND LOCATION IN (locationList) 
    AND TYPE IN (typeList) 
    AND NOTE contains[cd] "some text" 
    AND DATE >= fromDate 
    AND DATE <+ toDate 

我和如何建立以此爲NSPredicate與核心數據使用掙扎。我已閱讀文檔......僅提供簡單的示例。如果有人能指點我一個更復雜的例子,我一定會很感激。


那麼,我在這裏有兩年的答案,很多人發現有幫助。我的帖子已被刪除。這裏是解決方案的更新網址。

https://www.radeeccles.com/convert-sql-statement-to-an-nspredicate-for-use-with-core-data/

+0

您是否嘗試在謂詞中輸入where子句?它有一個方法來建立一個非常強大的字符串。 – 2010-10-17 23:15:04

+0

我不知道任何讓我指定一個生成謂詞的SQL語句的地方。請指教。 – radesix 2010-10-18 22:53:49

+0

我不知道爲什麼我的帖子不斷被刪除。這篇文章已經幫助了許多人http://www.radeeccles.com/convert-sql-statement-to-an-nspredicate-for-use-with-core-data/ – radesix 2013-03-13 16:29:18

回答

9

你需要做的是建立一個謂語爲您的條款的每一個。例如,讓我們打破你的查詢:

  1. SELECT * FROM交易
  2. WHERE類別中(所屬分類)
  3. 和位置(locationList)
  4. 和類型(TYPELIST)
  5. 和註釋包含苯並[cd] 「一些文本」
  6. AND DATE> = FROM日期AND DATE < + TODATE

基於此,您有5個謂詞(2-6)。所以我們一個接一個地研究它們。

NSPredicate *inCategoryPredicate = [NSPredicate predicateWithFormat:@"Category IN %@", categoryList]; 

NSPredicate *locationPredicate = [NSPredicate predicateWithFormat:@"Location IN %@", locationList]; 

NSPredicate *typePredicate = [NSPredicate predicateWithFormat:@"Type IN %@", typeList]; 

NSPredicate *notePredicate = [NSPredicate predicateWithFormat:@"Note contains[c] %@", @"Some Text"]; 

NSPredicate *startDatePredicate = [NSPredicate predicateWithFormat:@"Date => @", fromDate]; 

NSPredicate *endDatePredicate = [NSPredicate predicateWithFormat:@"Date <= @", toDate]; 

現在,你只需要它們連接成只有一個謂語:Apple's documentation states

你應該結構的複合謂詞,以儘量減少做 的工作量。正則表達式匹配尤其是一個昂貴的操作 操作。在複合謂詞中,因此,應該在正則表達式之前執行簡單測試 ;

這就是說,你應該首先從「易」謂詞開始。所以:

NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects: startDatePredicate, endDatePredicate, inCategoryPredicate, locationPredicate, typePredicate, notePredicate]; 

如果你使用NSLog,你總是可以知道謂詞(sql where)的樣子。

+0

是否可以回答[這個問題](https ://stackoverflow.com/questions/46388393/create-complicated-nscompoundpredicate-in-swift-3)? – 2017-09-24 09:46:51

相關問題