# Countdown timer in every table cell

I am making countdown app with multiple records, so I am using UITableView to show that records and countdown dates. What I do is just take one timer and reload cells on every second. Is this a best approach to reload visible cells on every second or is there another better approach there?

updateCellContentsTimer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector: #selector(ViewController.updateCells),
userInfo: nil, repeats: true)

// MARK: Custom Functions

func updateCells() {
let indexPathsArray = tableView.indexPathsForVisibleRows
for indexPath in indexPathsArray! {
let cell = tableView.cellForRow(at: indexPath) as! CountdownTableViewCell

cell.timeLeftLabel.text = progress + "hours:minutes:seconds"
}
}

• Instead of reloading every cell on timer event you can use the notification mechanism of Cocoa. – Shial Apr 14 '17 at 1:28
• @Shial, since it's a countdown, every visible cell needs to change every second. Doing that indirectly through notifications only adds complexity without avoiding the cell updates. The OP already limits the updates to visible cells so the process is optimal. – Alain T. Apr 19 '17 at 13:22
• @AlainT. so this is the right way to update time in every cell .. right?? – EI Captain v2.0 Apr 21 '17 at 4:44
• Yes. What makes it right is that you use indexPathsForVisibleRows. This is the smallest number of cell updates that you can do for your countdown. Having only one timer to manage all the countdowns is also the optimal way to do it. – Alain T. Apr 21 '17 at 4:54
• @AlainT. thanks buddy ... thanks for your suggestion .. really appreciate :) – EI Captain v2.0 Apr 21 '17 at 5:00

to avoid DRY i would put this line (i think it is in your code only a sample logic) inside the cell. in this case you have the logic for calculating the remaining time inside the cell and not outside somewhere. and you can use always the same function to update the progress.

cell.timeLeftLabel.text = progress + "hours:minutes:seconds"


should be become

cell.updateProgress()