How to filter CGPoints in an NSArray by CGRect

cocoa-touch, ios, nsarray, objective-c

Solution

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.

Problem

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]; ```

Original source