简体   繁体   中英

iOS: NSRunLoop on a Custom Cell

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()
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM