I have an application that contains some Locations in Core Data, and I want to show them to the user in order of proximity to the user's location. I am using an NSFetchedResultsController to serve the locations to the Table View. I thought about creating a virtual accessor method that returns the location's distance from the user, that would be calculated using a "global" CoreLocationManager, but it crashes with reason:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath distanceFromCurrentLocation not found in entity < NSSQLEntity Location id=4>'
I also give the user the option to sort alphabetically, so I would prefer it if I kept the NSFetchedResultsController, if possible.
How should I do it?
Thanks!
The problem (or missing feature) of NSFetchedResultsController is the missing capability to use transient attributes for sort order and section key path.
I struggled with this as well, so you might be interested in this:
NSFetchedResultsController sections localized sorted
I'm sure you could use this approach as well if you could guarantee a limited set of records. But I really would love to see a more sophisticated solution.
Virtual accessors won't work in Core Data unless you have a transient attribute defined in the entity. NSFetchedResultsController (and all other Core Data operations) look at the graph of entities before they try to perform any operation. If the virtual property does not show up in the entity definition, then NSFetchedResultsController will report that no such attribute exist.
You want to define a transient attribute in the entity with the name distanceFromCurrentLocation
and you should be able to write a virtual accessors and have the NSFetchedResultsController see it.
I tried to do the same thing, to sort results by the distance from a location. Here's one of my questions:
Core Data and Core Location
It turned out that you have to load all the locations into memory to compare them. I ended up using SQLite, which is more difficult to implement but caused me far fewer headaches for this kind of function.
It's probably not the answer you want, but if you have a large data set, I'd recommend SQLite. It ended up being faster and easier to deal with for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With