3lvis / DATASource

Core Data's NSFetchedResultsController wrapper for UITableView and UICollectionView
Other
106 stars 27 forks source link

Sorting by distance #106

Closed dneykov closed 7 years ago

dneykov commented 7 years ago

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.

3lvis commented 7 years ago

Hi @dneykov,

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

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

dneykov commented 7 years ago

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

3lvis commented 7 years ago

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.

dneykov commented 7 years ago

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)
        })
3lvis commented 7 years ago

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

dneykov commented 7 years ago

@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