开发者

Sort NSFetchedResultsController results by user location

开发者 https://www.devze.com 2022-12-27 15:45 出处:网络
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 th

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 n开发者_StackOverflow中文版ot 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号