【问题标题】:Quick Explanation of SUBQUERY in NSPredicate ExpressionNSPredicate 表达式中 SUBQUERY 的快速解释
【发布时间】:2010-09-28 08:36:43
【问题描述】:

Apple 关于 SUBQUERY 关键字的文档似乎为零,我在 SO 或 Google 上找不到关于它的简单解释。这是一个阴谋! ;)

,能否请内圈的人快速解释一下它的语法,以便我可以使用它?

SUBQUERY(Bs, $x, $x IN %@)

谢谢

【问题讨论】:

    标签: iphone cocoa cocoa-touch subquery nspredicate


    【解决方案1】:

    对于不太了解文档内容的人来说,SUBQUERY 本质上是这样的:

    SUBQUERY(collection, variableName, predicateFormat)
    

    并且可以(简单地)像这样实现:

    id resultingCollection = ...; //a new collection, either a mutable set or array
    NSMutableDictionary * substitutions = [NSMutableDictionary dictionary];
    NSPredicate * p = [NSPredicate predicateWithFormat:predicateFormat];
    for (id variable in collection) {
      [substitutions setObject:variable forKey:variableName];
      NSPredicate * filter = [p predicateWithSubstitutionVariables:substitutions];
      if ([filter evaluateWithObject:collection] == YES) {
        [resultingCollection addObject:variable];
      }
    }
    return resultingCollection;
    

    所以简而言之,SUBQUERY 基本上是获取对象的集合,并根据SUBQUERY 的谓词表达式过滤掉各种对象,并返回结果集合。 (而且谓词本身可以包含其他SUBQUERYs)

    例子:

    NSArray * arrayOfArrays = [NSArray arrayWithObjects:
                               [NSArray arrayWithObjects:....],
                               [NSArray arrayWithObjects:....],
                               [NSArray arrayWithObjects:....],
                               [NSArray arrayWithObjects:....],
                               [NSArray arrayWithObjects:....],
                               [NSArray arrayWithObjects:....],
                               nil];
    NSPredicate * filter = [NSPredicate predicateWithFormat:@"SUBQUERY(SELF, $a, $a.@count > 42)"];
    NSArray * filtered = [arrayOfArrays filteredArrayUsingPredicate:filter];
    //"filtered" is an array of arrays
    //the only arrays in "filtered" will have at least 42 elements each
    

    【讨论】:

    • 您的 NSPredicate 无法编译:捕获 "NSInvalidArgumentException"、"无法解析格式字符串 "SUBQUERY(SELF, $a, $a.@count > 2)""
    • @cfisher 次要更正:这是运行时错误,而不是编译错误。 (不是想成为一个混蛋。)
    【解决方案2】:

    This is what a subquery evaluates to.(来自this mailing list thread,在 Google 中“NSPredicate 子查询”排名第一。)该文档还解释了谓词格式字符串语法与它的关系。

    【讨论】:

    • 该死!我不敢相信我错过了。非常感谢。
    • 你怎么知道用什么字母?有些地方我看到了 $x 有些地方我看到了 $s,有些地方我看到了 $a,而且我无法通过上下文看到 $x 和 $s 之间的任何差异。
    • @orange80:变量名由您选择。请参阅我在答案中链接到的文档。如果你知道 Python,就像说[x for x in collection if (some condition involving x)]。据我所知,变量名甚至不必是单个字母。
    • 请注意:此时此帖子是谷歌首次点击“nspresicate subquery”:) +1 链接
    【解决方案3】:

    子查询表示一个谓词(第三个参数 - $x IN %@),它在关系(第一个参数 - Bs)的所有对象(第二个参数 - $x - 它就像 foreach 中的变量名)上进行评估。与常规查询类似,返回对象列表。

    我在很多地方看到人们几乎教条地使用$x,但objects 关系中的$object 也很有意义(或$city 中的$city...):)

    前段时间我写了一篇关于SUBQUERY 的博文。您可以查看here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 2020-06-18
      相关资源
      最近更新 更多