Hibernia Hibernia - 1 year ago 70
iOS Question

Sorting arrays causes wrong data to be displayed into cells

I've got an array of rooms I'm wanting to filter by usercount/topvotes sorta stuff.

I'm hitting buttons to trigger the filter changes and set a value to "CurrentSearch", reloading my tabledata, and in my cellForRowAtIndexPath I'm checking the current currentsearch value and filtering the list accordingly.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

if currentSearch == "new" {
self.PersonalSearchesList = PersonalSearchesList.sorted{ $0.users < $1.users }

} else if currentSearch == "top" {

self.PersonalSearchesList = self.PersonalSearchesList.sorted{ $0.latestUser < $1.latestUser }


My images/labels load in perfectly fine before the filtering. On the initial load I'm setting currentSearch to "new" and it works perfectly. It's only once I start trying to swap between filters that things get funky. I'm getting random duplicates of cells, and while I'm swapping between the filters the incorrect loads stay consistent..as in the same duplicates of the same cells are being made/placed at the same spots.

I have it when I click on a cell the information for the cell is printed..and despite the cell information being loaded incorrectly the actual information is correct and the lists are ordered as they should be.

any ideas?

Answer Source

You should do something like this:

var currentSearch: String {
  didSet {
     // sort your array
    tableView?.reloadData() // reload data
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download