How to fetch managed objects sorted by calculated value

Posted by Marcin Zbijowski on Stack Overflow See other posts from Stack Overflow or by Marcin Zbijowski
Published on 2010-05-07T11:53:12Z Indexed on 2010/05/07 12:18 UTC
Read the original article Hit count: 201

Hello,

I'm working on the app that uses CoreData. There is location entity that holds latitude and longitude values. I'd like to fetch those entities sorted by distance to the user's location. I tried to set sort descriptor to distance formula sqrt ((x1 - x2)^2 + (y1 - y2)^2) but it fails with exception "... keypath ... not found in entity".

NSString *distanceFormula = [NSString stringWithFormat:@"sqrt(((latitude - %f) * (latitude - %f)) + ((longitude - %f) * (longitude - %f)))", 
                            location.coordinate.latitude, 
                            location.coordinate.latitude, 
                            location.coordinate.longitude, 
                            location.coordinate.longitude];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:distanceFormula ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSError *error;
NSArray *result = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];

I'd like to fetch already sorted objects rather then fetch them all and then sort in the code.

Any tips appreciated.

© Stack Overflow or respective owner

Related posts about iphone

Related posts about coredata