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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With