views:

191

answers:

3

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!

A: 

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.

TechZen
I get the same crash when using a transient property.. Only when making it a standard property it does work, but then it's conceptionally wrong i guess..
cgp
Not sure what you're trying to do exactly. Are you storing the locations in Core Data entities or are you trying to use Core Data to organize the locations for display in a table without inserting them into entities first? If its the later, then that won't work.
TechZen
A: 

I tried to do the same thing, to sort results by the distance from a location. Here's one of my questions:

http://stackoverflow.com/questions/2176127/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.

nevan
Unfortunately SQLite is not an option for me, as I need to use existing Core Data databases... Thanks for the tip anyway ;)
cgp
A: 

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:

http://stackoverflow.com/questions/2744387/nsfetchedresultscontroller-sections-localized-sorted/2770948#2770948

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.

Gerd