Try to search your question here, if you can't find : Ask Any Question Now ?

CoreData Predicate with Function Argument

HomeCategory: stackoverflowCoreData Predicate with Function Argument
Avatarkundan asked 5 months ago

I am attempting to include a function in a Predicate definition. Is this possible?

Let’s say you have a Core Data entity of Places with attributes for
latitude and longitude.

I would like to add annotations to a mapview of those Places within a
specified distance from the user location. I can, of course, loop through the entire database and calculate the distance between each Place and the
user location but I will have about 35000 places and it would seem that
it would be more efficient to have a predicate in the
fetchedResultsController setup.

I tried the code below but I receive an error message of “Problem with
subpredicate BLOCKPREDICATE(0x2808237b0) with userInfo of (null)”

func myDistanceFilter(myLat : CLLocationDegrees, myLong : CLLocationDegrees, cdLat : CLLocationDegrees, cdLong : CLLocationDegrees) -> Bool {

    let myLocation = CLLocation(latitude: myLat, longitude: myLong)
    let cdLocation = CLLocation(latitude: cdLat, longitude: cdLong)

    if myLocation.distance(from: cdLocation) < 5000.0 {
        return true
    } else {
        return false

And inside the fetchedResultsController:

let distancePredicate = NSPredicate {_,_ in self.myDistanceFilter(myLat: 37.774929, myLong: -122.419418, cdLat: 38.0, cdLong: -122.0)}

If it is possible to have a block/function inside a predicate how do you get a reference to an attribute for the entity object being evaluated?

Any guidance would be appreciated.

1 Answers
Best Answer
AvatarMannu answered 5 months ago
Your Answer

1 + 13 =

Popular Tags

WP Facebook Auto Publish Powered By :