Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 674
TheOne Avatar asked Dec 28 '22 00:12

TheOne


1 Answers

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.

like image 119
omz Avatar answered Jan 15 '23 00:01

omz