Search code examples
swifttimertableviewrunloop

Swift RunLoop blocks table view


So, I have a timer which increments a variable by one in my app delegate every 0.1 seconds. In my tableViewController, I have this number displayed in a cell. In the controller there is ANOTHER timer which reloads visible cells. Everything worked, apart for the fact that once scrolling through the tableView, the number stopped changing until the table view wasn't released. I have read that the fix for this was:

RunLoop.current.add(tableTimer, forMode: RunLoopMode.commonModes)

Where tableTimer is my cell reload timer. Nevertheless, this works, but once scrolling through the view it is extremely laggy and is 0% fluid, as it normally is. Any fix? Thanks.

EDIT:

Creating the timer:

func scheduledTimerWithTimeInterval(){
    reloadTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.reloadTV), userInfo: nil, repeats: true)
    RunLoop.current.add(earningTimer, forMode: RunLoopMode.commonModes)
}

Updating table view:

@objc func reloadTV() {
    self.tableView.beginUpdates()
    self.tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows!, with: .none)
    self.tableView.endUpdates()
}

Solution

  • Reloading a table view every .1 seconds for a label in a cell is quite stupid. For many several reasons. The optimum way to solve this issue is to loop through all visible index paths, create a cellForRowAtIndexPath with the index paths and than modify the cell title directly from there, in the following way:

    @objc func reloadTV() {
    
        for myIP in (tableView.indexPathsForVisibleRows) {
            let cell = tableView.cellForRow(at: myIP)
            cell.textLabel?.text = changingVariable
        }
    
    }