你需要做的是建立一個謂語爲您的條款的每一個。例如,讓我們打破你的查詢:
- SELECT * FROM交易
- WHERE類別中(所屬分類)
- 和位置(locationList)
- 和類型(TYPELIST)
- 和註釋包含苯並[cd] 「一些文本」
- 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)的樣子。
您是否嘗試在謂詞中輸入where子句?它有一個方法來建立一個非常強大的字符串。 – 2010-10-17 23:15:04
我不知道任何讓我指定一個生成謂詞的SQL語句的地方。請指教。 – radesix 2010-10-18 22:53:49
我不知道爲什麼我的帖子不斷被刪除。這篇文章已經幫助了許多人http://www.radeeccles.com/convert-sql-statement-to-an-nspredicate-for-use-with-core-data/ – radesix 2013-03-13 16:29:18