NSSortDescriptor - sort by location

笑着哭i 提交于 2019-12-05 13:40:27

Objective-C based sort descriptors cannot be used with a fetch request.

From the "Core Data Programming Guide":

... To summarize, though, if you execute a fetch directly, you should typically not add Objective-C-based predicates or sort descriptors to the fetch request. Instead you should apply these to the results of the fetch.

A different take on this would be to have a property on your 'Stop' managedObject called meanSquared (probably an NSDecimalNumber).

When your device lat/long has moved sufficiently to alter the 'nearest Stop' data, then you update all 'Stop' objects with the meanSquared distance (i.e. (yourLat-stopLat)^2+(yourLong-stopLong)^2), then just use 'meanSquared' in your sortDescriptor.

Depending on the number of times that you update the user's position, the distance between stops and the number of stops this might be an optimal solution.

You can't sort by lat/Lon anyway, you'll need to compute distance for each point and sort by that. Or fetch a range of lat/Lon values near the user, fetch that subset, compute distance for them and display. range would be like user's lat +/- 0.1 degrees, etc for the fetch.

I would recommend the following approach:

See the 'Geo-Location Predicate' section of http://www.objc.io/issue-4/core-data-fetch-requests.html

It gets approximate results using a predicate and then sorts them accurately in-memory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!