【发布时间】:2010-09-28 08:36:43
【问题描述】:
Apple 关于 SUBQUERY 关键字的文档似乎为零,我在 SO 或 Google 上找不到关于它的简单解释。这是一个阴谋! ;)
请,能否请内圈的人快速解释一下它的语法,以便我可以使用它?
SUBQUERY(Bs, $x, $x IN %@)
谢谢
【问题讨论】:
标签: iphone cocoa cocoa-touch subquery nspredicate
Apple 关于 SUBQUERY 关键字的文档似乎为零,我在 SO 或 Google 上找不到关于它的简单解释。这是一个阴谋! ;)
请,能否请内圈的人快速解释一下它的语法,以便我可以使用它?
SUBQUERY(Bs, $x, $x IN %@)
谢谢
【问题讨论】:
标签: iphone cocoa cocoa-touch subquery nspredicate
对于不太了解文档内容的人来说,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
【讨论】:
This is what a subquery evaluates to.(来自this mailing list thread,在 Google 中“NSPredicate 子查询”排名第一。)该文档还解释了谓词格式字符串语法与它的关系。
【讨论】:
[x for x in collection if (some condition involving x)]。据我所知,变量名甚至不必是单个字母。
子查询表示一个谓词(第三个参数 - $x IN %@),它在关系(第一个参数 - Bs)的所有对象(第二个参数 - $x - 它就像 foreach 中的变量名)上进行评估。与常规查询类似,返回对象列表。
我在很多地方看到人们几乎教条地使用$x,但objects 关系中的$object 也很有意义(或$city 中的$city...):)
前段时间我写了一篇关于SUBQUERY 的博文。您可以查看here。
【讨论】: