【问题标题】:Complicated NSPredicates: comparing values on the most-recent object复杂的 NSPredicates:比较最近对象的值
【发布时间】:2012-12-20 00:22:29
【问题描述】:

我正在尝试解决一个复杂的谓词。

基本上,我有一个 Student 对象。学生有 testScoreObjects。 TestScoreObject 具有 scoreDate (NSDate) 和 score (NSNumber) 等属性。

我想要一个最近(按 scoreDate)TestScoreObject 的分数大于 n 的学生列表。

理想情况下,在 NSFetchedResultsController 上使用一个 NSPredicate 会很好。

我知道如何通过查看所有学生以编程方式完成此任务,但我想知道这是否可以通过谓词来完成,这样我就可以保留拥有 FetchedResultsController 的所有美妙好处。

感谢您的所有帮助!

【问题讨论】:

    标签: ios core-data nspredicate


    【解决方案1】:

    我会使用以下谓词:

    NSString *format = @"SUBQUERY(testScoreObjects, $each, $each.score > $n && $each.scoreDate == testScoreObjects.@max.scoreDate)[SIZE] > 0";
    NSDictionary *substitutions = @{@"n": @3}; // 3 is the value for n
    NSPredicate *predicate = [[NSPredicate predicateWithFormat:format] predicateWithSubstitutionVariables:substitutions];
    

    NSString *format = @"ANY SUBQUERY(testScoreObjects, $each, $each.score > $n).scoreDate == testScoreObjects.@max.scoreDate";
    NSDictionary *substitutions = @{@"n": @3}; // 3 is the value for n
    NSPredicate *predicate = [[NSPredicate predicateWithFormat:format] predicateWithSubstitutionVariables:substitutions];
    

    两者都可以正常过滤数组,但我还没有测试 CoreData 是否能够将它们转换为 SQL(因此它可以与 fetch 请求一起使用)。

    在处理大型商店时,第二个谓词应该更有效(据我所知),因为每个学生只评估一次 testScoreObjects.@max.scoreDate。当然,实际结果可能会有所不同。

    【讨论】:

    • 感谢您的建议。这些在过滤数组时确实有效,但 Core Data 真的不喜欢@max。哦,好吧,我们会找到另一种方法!
    【解决方案2】:

    当涉及到对象图时,子查询实际上是 SQL 继承的拐杖。我认为你可以没有那个。看看事情有多么简单:

    [NSPredicate predicateWithFormat:
         @"ANY testScores.scoreDate > %@", cutoffDate];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-01
      • 2012-05-14
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多