iphone - NSPredicate 表达式中 SUBQUERY 的快速解释

标签 iphone cocoa cocoa-touch subquery nspredicate

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

拜托,内部圈子的人可以快速解释一下它的语法,以便我可以使用它吗?

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

谢谢

最佳答案

对于不太明白文档内容的人来说,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 的谓词表达式过滤出各种对象,然后返回结果集合。 (谓词本身可以包含其他 SUBQUERY)

示例:

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

关于iphone - NSPredicate 表达式中 SUBQUERY 的快速解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3810992/

相关文章:

iphone - 如何在后台中断后恢复 AVAudioPlayer

iphone - ios - 代码 VS Storyboard 意见

macos - 将 Cocoa 实用程序应用程序拆分为辅助二进制文件 + 主应用程序二进制文件的优点和缺点?

Objective-C:NSURLConnection 响应?

objective-c - TableView 绑定(bind)中的特定行内容

ios - iOS 6 中的模态视图 Controller 强制横向方向

iPhone - UIView 方向更改

ios - 无法使用 SLComposeServiceViewController 隐藏键盘

iphone - objective-C : How can I freeze the screen and add loading animation?

iphone - UIPickerView:旋转时获取行值?