3lvis / DATASource

Core Data's NSFetchedResultsController wrapper for UITableView and UICollectionView

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Sorting by distance

dneykov opened this issue · comments

Hi,
I'm loading a list of locations in tableView. I have a model with fields "latitude" and "longitude" and I want to sort this list by distance using my current location. How can I sort dataSource?
Thanks.

Hi @dneykov,

Doesn't seem that transient properties are supported for Core Data sort descriptors.

https://stackoverflow.com/a/13758006/717416

I was wondering if its possible some how to sort all objects using sort() function on dataSource.all()

you can use the sortDescriptor for distance but it means you will need a distance attribute that gets updated every time your current location changes.

Can I sort it in memory after it's fetched from CoreData? I'm trying something like that but is not working:

self.dataSource.all().sort({ (objectOne, objectTwo) in
            guard let _objectOne = objectOne as? Object else { return false }
            guard let _objectTwo = objectTwo as? Object else { return false }
            
            return _objectOne.distance(to: lastKnownLocation) < _objectTwo.distance(to: lastKnownLocation)
        })

@dneykov I don't think NSFetchedResultsController works with in-memory data, you need to store it in disk.

@3lvis I took your advise to update distance attribute. Every time before segue to that list view i'm updating distance attribute with last know location and it works perfectly.
Not sure if it's the right way but is working :)

Thanks