2010-10-17 110 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

相关问题