I want to sort the results of my Parse Query based on the scalar distance from the field temperature
to my variable referenceTemp
I tried the following, which of course does not work, but it illustrates my intention
var referenceTemp = 47.89
var query = PFQuery(className: "Temperatures")
query.orderByAscending("abs(temperature - referenceTemp)")
How can I do it? Thanks!!
You can't do this on the database level... but you can do it with two queries:
var referenceTemp = 47.89
var query = PFQuery(className: "Temperatures")
query.greaterThan(referenceTemp);
query.orderByAscending();
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
//Get the scalar distance for each, store
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
query.lessThan(referenceTemp);
query.orderByDescending();
query.findObjectsInBackgroundWithBlock...
Once you have both the closest above and below, and their scalar distances, you could use a hash or an NSDictionary with keys of scalar distance and values of the objects. Order as needed and you're there in only 2 queries.