我需要用许多数据构建一个NSPredicate。例如,在SQL中,我将执行如下操作:
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。我看过文件..。只提供了一些简单的例子。如果有人能给我举一个更复杂的例子,我肯定会很感激的。
嗯,我在这两年里得到了一个答案,很多人都觉得很有帮助。我的帖子被删除了。下面是更新的URL和解决方案。
https://www.radeeccles.com/convert-sql-statement-to-an-nspredicate-for-use-with-core-data/
发布于 2013-03-13 16:27:31
您需要做的是为每个子句创建一个谓词。例如,让我们分析一下您的查询:
从TRANSACTIONS
H 111和DATE >= fromDate和DATE <+ H 212G 213
基于此,您有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 )是什么样子的。
https://stackoverflow.com/questions/3955717
复制相似问题