Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update UITableView every second

I am wondering what is the proper way of showing countdown in fairly complex UITableViewCells, in each cell one countdown with different time.

I could have NSTimer for each cell separately but then the cells wouldnt update at same time. I could have one NSTimer for all cells but calling reloadData on uitableview is fairly expensive to do every second, isnt it?

Obviously the needs to be updated only in visible cells.

Any ideas, best practice, know how on this matter?

like image 712
Zdeněk Topič Avatar asked Mar 18 '23 05:03

Zdeněk Topič


2 Answers

Some thoughts on how I would implement this:

  • Create a custom class for the cell's prototype and implement an update method in that class. This method updates the label.
  • Create the timer in the custom TableViewController class
  • Whenever the timer fires, iterate through the cells via the indexPath. UITableView.CellForRowAtIndexPath returns nil for cells which aren't visible.
  • Call the cell's update method for each of these visible cells.
like image 128
zisoft Avatar answered Mar 31 '23 16:03

zisoft


An alternative approach would be to use NSNotificationCenter.

  • Your view controller would post a notification whenever your time period has elapsed.

  • Each of your UITableViewCell would register for this notification and update its display in response.

Note that to prevent memory leaks you need to remove each UITableViewCell as an observer as it goes off-screen. This can easily be done in the UITableViewDelegate's tableView:didEndDisplayingCell:forRowAtIndexPath: method.

The advantage of doing this is that you don't need to subclass UITableViewCell nor to try and keep track of each cell that needs refreshing.

like image 39
Clafou Avatar answered Mar 31 '23 17:03

Clafou