Reputation: 77631
I have an entity in CoreData MyObject
which has properties latitude
and longitude
.
I'd like to perform a fetch with an NSFetchedResultsController
that sorts the fetch by the distance the MyObject
is from the user's current location.
However, I don't know what to put in the Key
part of the sort descriptor.
I don't want to compare a particular key of the object. I want to compare the objects themselves.
I'm not sure how it's possible for me to do this without repopulating the distance field of the records.
I'm trying to use this code...
[[NSSortDescriptor alloc] initWithKey:@"." ascending:YES comparator:^NSComparisonResult(MyObject *object1, MyObject *opject2) {
// stuff here
}];
But it crashes the app due to memory pressure (lol).
Obviously using @"."
is not correct but is there a way of doing this?
Or is there a better way of doing this using a different approach?
Upvotes: 1
Views: 756
Reputation: 3661
If you don't want to sort the objects by their keys but instead sort the objects themselves then you should not use Sort descriptors. Just get the array of the results and then sort that array. Of course your custom object MyObject should implement isEqual in order to do this.
Another alternative is to add a new key called distance
to the MyObject and then use it as the key for the sort descriptor.
executeFetchRequest
to fetch all the locations in the database. distance
performFetch
fetchedObjects
of the FRC which will be in sorted order according to the distance
.Hope this works for you.
Upvotes: 2