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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.