ios - Sort NSFetchRequest by calculation result -
so have dataset of points latitude , longitude values , want retrieve them , sort them distance user's current location. currently, have following:
mainmoc.performblockandwait { // fetching data coredata let fetchrequest = nsfetchrequest() fetchrequest.predicate = nspredicate(format: "pointlatitude between {%f,%f} , pointlongitude between {%f,%f}", (latitude-0.03), (latitude+0.03), (longitude-0.03), (longitude+0.03)) let entity = nsentitydescription.entityforname("pointprimary", inmanagedobjectcontext: self.mainmoc) fetchrequest.entity = entity let sortdescriptor = nssortdescriptor(key: "pointtitle", ascending: false) fetchrequest.sortdescriptors = [sortdescriptor] { points = try self.mainmoc.executefetchrequest(fetchrequest) as! [pointprimary] } catch { let jsonerror = error nserror nslog("\(jsonerror), \(jsonerror.localizeddescription)") abort() } } so i'm sorting based on title. how proceed if wanted calculate distance cllocationcoordinate2d , sort fetchrequest results based on that?
thanks bunch!
this should work. you'll use nssortdescriptor custom comparator.
the trick use "self" key nssortdescriptor, pass fetched objects comparator.
var userlocation : cllocation // somewhere var distancecompare : nscomparator = { (obj1: anyobject!, obj2: anyobject!) -> nscomparisonresult in let lng1 = obj1.valueforkey("pointlongitude") as! cllocationdegrees let lat1 = obj1.valueforkey("pointlatitude") as! cllocationdegrees let p1location : cllocation = cllocation(latitude: lat1, longitude: lng1) let p1distancetouserlocation = userlocation.distancefromlocation(p1location) let lng2 = obj2.valueforkey("pointlongitude") as! cllocationdegrees let lat2 = obj2.valueforkey("pointlatitude") as! cllocationdegrees let p2location : cllocation = cllocation(latitude: lat1, longitude: lng1) let p2distancetouserlocation = userlocation.distancefromlocation(p2location) if (p1distancetouserlocation > p2distancetouserlocation) { return .ordereddescending } else if (p1distancetouserlocation < p2distancetouserlocation) { return .orderedascending } else { return .orderedsame } } var distancesortdescriptor = nssortdescriptor(key: "self", ascending: true, comparator: distancecompare) fetchrequest.sortdescriptors = [distancesortdescriptor]
Comments
Post a Comment