I am run NSRunLoop
with NSTimer
on a custom cell in order to continuously update the "Valid Until" UILabel
. It works fine until I close the tableView, the NSRunLoop
continues the time countdown. I use dealloc
, but seems it doesn't drain NSRunLoop
and NSTimer
.
-(void)dealloc {
[[NSNotificationCenter defaultCenter]removeObserver:self];
[_timer invalidate];
CFRunLoopStop(CFRunLoopGetCurrent());
_runner = nil; // NSRunLoop
}
How can I kill the NSRunLoop
when a cell gets released? Thank you in advance.
Approaching the problem using the current run loop will get you in all kinds of trouble. The simplest way to approach the problem is by having an NSTimer
property on your cell and start/stop it when the cell willDisplay
/willEndDisplay
.
class CustomCell: UITableViewCell {
var timer: NSTimer?
func startTimer() -> Void {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateUI:", userInfo: nil, repeats: true)
}
func stopTimer() -> Void {
timer?.invalidate()
timer = nil
}
func updateUI(sender: NSTimer?) -> Void {
// update your label here
}
}
class ViewController: UIViewController, UITableViewDelegate {
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? CustomCell {
cell.startTimer()
}
}
func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? CustomCell {
cell.stopTimer()
}
}
}