TheOne
TheOne

Reputation: 11161

How to filter CGPoints in an NSArray by CGRect

I have an NSArray with CGPoints. I'd like to filter this array by only including points within a rect.

How can I formulate an NSPredicate such that each point satisfies this predicate:

CGRectContainsPoint(windowRect, point);

Here's the code so far:

NSArray *points = [NSArray arrayWithObjects: [NSValue valueWithCGPoint:pointAtYZero] ,
                                             [NSValue valueWithCGPoint:pointAtYHeight],
                                             [NSValue valueWithCGPoint:pointAtXZero],
                                             [NSValue valueWithCGPoint:pointAtXWidth],
                                             nil];


NSPredicate *inWindowPredicate = [NSPredicate predicateWithFormat:@"CGRectContainsPoint(windowRect, [point CGPointValue])"];
NSArray *filteredPoints = [points filteredArrayUsingPredicate:inWindowPredicate];

Upvotes: 4

Views: 816

Answers (1)

omz
omz

Reputation: 53561

You cannot do this with the predicate format syntax, but you can use a block:

NSArray *points = ...;
CGRect windowRect = ...;    
NSPredicate *inWindowPredicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    CGPoint point = [evaluatedObject CGPointValue];
    return CGRectContainsPoint(windowRect, point);
}];
NSArray *filteredPoints = [points filteredArrayUsingPredicate:inWindowPredicate];

Note that it's not possible to use block-based predicates for Core Data fetch requests.

Upvotes: 10

Related Questions