一个可以递归遍历对象图的 NSPredicate? [英] An NSPredicate that can recursively traverse an object graph?

查看:36
本文介绍了一个可以递归遍历对象图的 NSPredicate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试过滤基本上形成树形图的对象数组.我想要做的是从这个数组中过滤掉所有可见属性为 NO 的对象,或者如果它的父/祖父/等可见属性为真(子对象的可见属性可以是 YES,而其父对象可以是 NO).

我不清楚我将如何使用 NSPredicate 语法继续搜索父节点,直到没有父节点或找到可见属性.有什么办法可以解决这个问题吗?

解决方案

我问这个问题已经有一段时间了,我想我在做的事情的另一个方向,但我现在意识到有一些可能性需要解决我当时想要的:

  • 让可见属性方法以递归方式运行,而不是让格式谓词这样做.这可以像这样完成:
<块引用>

- (BOOL) isVisible {返回可见 &&[父母是可见的];}//...id 过滤 = [数组过滤数组UsingPredicate:[NSPredicate predicateWithFormat:@"visible == YES"]];

  • 使用块谓词代替格式谓词进行递归遍历:
<块引用>

[arrayfilteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(idevaluateObject, NSDictionary *bindings) {id obj = 评估对象;而(对象){if (![obj isVisible]) 返回 NO;obj = [obj 父对象];}返回是;}]];

或者两者的组合(我认为这将是最健壮和可读的).

I'm trying to filter an array of objects that essentially form a tree-style graph. what i want to do is to filter out all objects from this array whose visible property is NO, or if its parent/grandparent/etc visible property is true (child objects can have the visible property be YES while its parent can be NO).

I'm unclear as to how i would go about this using NSPredicate syntax to keep searching the parent node until there are no parents or the visible property is found. Is there any way to go about this?

解决方案

Its been awhile since I asked this question, and I think I went in another direction with what i was doing, but there are some possibilities i realize now to solve what i wanted at the time:

  • Have the visible property method behave recursively instead of making the format predicate do that. This could be accomplished like so:

- (BOOL) isVisible {
  return visible && [parent isVisible];
}

//...
id filtered = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"visible == YES"]];

  • Use block predicates instead of format predicates to do the recursive traversal:

[array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {

    id obj = evaluatedObject;
    while (obj) {
      if (![obj isVisible]) return NO;
      obj = [obj parent];
    }
    return YES;
}]];

Or a combination of the two (which would be the most robust and readable I think).

这篇关于一个可以递归遍历对象图的 NSPredicate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆