Search code examples
objective-cioscore-datanspredicatecllocation

Distance Between Locations Using NSPredicate


So I have a Core Data with an entity containing a longitude and latitude as NSNumbers. I want the NSFetchRequest's Predicate to filter based on how far the object in the database's location is from my current location. This would require me to convert the stored coordinates to CLLocationDegrees and then put them in a CLLocation object. Finally, I can do the compare with the CLLocation distanceFromLocation.

I worded this as best as I can, does anyone have any ideas how I can do this with an NSPredicate?

Thanks!


Solution

  • Try block-based predicate:

    CLLocationDistance maxDistance = 100.0;
    CLLocation *currentLocation = ...;
    
    NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id location, NSDictionary *bindings) {
        return [location distanceFromLocation:currentLocation] <= maxDistance;
    }];