ios - 从 NSArray 动态生成 NSPredicate

标签 ios nspredicate

我有大量不同的 NSObject 类型,它们都具有不同的属性,我正在尝试抽象出一个方法,该方法允许我通过简单地传入我希望过滤的属性的 NSArray 来过滤对象的 NSArray在。我过滤的数字键可能从 1 到任何值不等。

这里是一个过滤NSArray的例子

NSArray *filterBy = [NSArray arrayWithObjects:
                       @"ManufacturerID",
                       @"CustomerNumber",nil];

这些键也存在于我正在过滤的 NSArray 的对象中,所以基本上这需要生成如下内容:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K == %@ AND %K == %@",
                       [filterBy objectAtIndex:0], 
                       [items valueForKey: [filterBy objectAtindex:0],
                       [filterBy objectAtIndex:1], 
                       [items valueForKey: [filterBy objectAtIndex:1]];

这会生成如下内容:ManufacturerID==18 AND CustomerNumber=='WE543'

这有可能吗?

最佳答案

这很简单。检查一下:

NSMutableArray *subpredicates = [NSMutableArray array];
for (NSString *filterKey in filterBy) {
  NSString *filterValue = [items valueForKey:filterKey];
  NSPredicate *p = [NSPredicate predicateWithFormat:@"%K = %@", filterKey, filterValue];
  [subpredicates addObject:p];
}
NSPredicate *final = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];

关于ios - 从 NSArray 动态生成 NSPredicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11889728/

相关文章:

ios - 使用导航 Controller 在 Storyboard 中呈现 View Controller - Swift

ios - 采取包括设备框架的 iOS 模拟器屏幕截图?

ios - CoreData 获取请求 NSPredicate 不起作用

ios - UITableView 没有显示它应该显示的 Realm 对象

ios - 如何使用 NSPredicate 通过多文本查询搜索文本?

ios - 在 SKSpriteNode 上使用 resizableImageWithCapInsets

ios - 将值(value)传递给私有(private)属性(property)

ios - Swift:异步数据任务永远不会终止

ios - NSPredicate 用于 NSArray 的 NSArray 中对象的属性

iphone - 使用NSPredicate过滤NSArray