5
\$\begingroup\$

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"
    }
}
\$\endgroup\$
  • \$\begingroup\$ Instead of reloading every cell on timer event you can use the notification mechanism of Cocoa. \$\endgroup\$ – Shial Apr 14 '17 at 1:28
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – Alain T. Apr 19 '17 at 13:22
  • \$\begingroup\$ @AlainT. so this is the right way to update time in every cell .. right?? \$\endgroup\$ – EI Captain v2.0 Apr 21 '17 at 4:44
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Alain T. Apr 21 '17 at 4:54
  • \$\begingroup\$ @AlainT. thanks buddy ... thanks for your suggestion .. really appreciate :) \$\endgroup\$ – EI Captain v2.0 Apr 21 '17 at 5:00
1
\$\begingroup\$

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()
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.