2015-11-11 86 views
0

我在自定义单元格上运行NSRunLoopNSTimer,以便不断更新“有效期”UILabel。它工作正常,直到我关闭tableView,NSRunLoop继续倒计时。我使用dealloc,但似乎不排水NSRunLoopNSTimeriOS:自定义单元格上的NSRunLoop

-(void)dealloc { 

    [[NSNotificationCenter defaultCenter]removeObserver:self]; 
    [_timer invalidate]; 
    CFRunLoopStop(CFRunLoopGetCurrent()); 
    _runner = nil; // NSRunLoop 
} 

当细胞获得释放时,我怎样才能杀死NSRunLoop?先谢谢你。

+2

我不会_dare_以这种方式使用NSRunLoop。你只是在问问题。 – gnasher729

+0

我对此声明投了票。 – NCFUSN

回答

2

使用当前运行循环来解决问题会给你带来各种麻烦。解决此问题的最简单方法是在单元上具有NSTimer属性,并在单元格为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() 
     } 
    } 

}