NSPredicate that can recursively intersect an object graph?

I am trying to filter out an array of objects that essentially form a tree graph. what I want to do is filter out all objects from this array whose visible property is NO, or its true parent property / grandparent / etc (children can have the visible property YES, and its parent can be NO).

It is unclear how I will use this using the NSPredicate syntax to continue searching for the parent node until the parents are found or the visible property is found. Is there any way to do this?

+3
source share
2 answers

It has been a while since I asked this question, and I think I went in a different direction with what I was doing, but there are some possibilities that I understand now to solve what I wanted at that time:

  • In order for the visible property method to work recursively, instead of making a format predicate, do this. This can be done like this:
- (BOOL) isVisible {
  return visible && [parent isVisible];
}

//...
id filtered = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"visible == YES"]];
  • Use block predicates instead of format predicates to perform 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 reliable and readable, I think).

+1
source

, , . , , BOOL, , .

NSMutableArray

for (int i = 0; i < [results count]; i++)
{
    if ([self shouldBeRemoved:[results objectAtIndex:i]])
    {
        [results removeObjectAtIndex:i];
        i--;
    }
}

shouldBeRemoved: .

0

Source: https://habr.com/ru/post/1733290/


All Articles