iOS:自定义单元格上的 NSRunLoop
iOS: NSRunLoop on a Custom Cell
我 运行 NSRunLoop
和 NSTimer
在自定义单元格上,以便不断更新 "Valid Until" UILabel
。它工作正常,直到我关闭 tableView,NSRunLoop
继续倒计时。我使用 dealloc
,但似乎它不会耗尽 NSRunLoop
和 NSTimer
。
-(void)dealloc {
[[NSNotificationCenter defaultCenter]removeObserver:self];
[_timer invalidate];
CFRunLoopStop(CFRunLoopGetCurrent());
_runner = nil; // NSRunLoop
}
如何在释放单元格时杀死 NSRunLoop
?提前谢谢你。
使用当前 运行 循环解决问题会给您带来各种麻烦。解决该问题的最简单方法是在您的单元格上设置 NSTimer
属性 并在单元格 willDisplay
/willEndDisplay
.[=14= 时设置 start/stop ]
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()
}
}
}
我 运行 NSRunLoop
和 NSTimer
在自定义单元格上,以便不断更新 "Valid Until" UILabel
。它工作正常,直到我关闭 tableView,NSRunLoop
继续倒计时。我使用 dealloc
,但似乎它不会耗尽 NSRunLoop
和 NSTimer
。
-(void)dealloc {
[[NSNotificationCenter defaultCenter]removeObserver:self];
[_timer invalidate];
CFRunLoopStop(CFRunLoopGetCurrent());
_runner = nil; // NSRunLoop
}
如何在释放单元格时杀死 NSRunLoop
?提前谢谢你。
使用当前 运行 循环解决问题会给您带来各种麻烦。解决该问题的最简单方法是在您的单元格上设置 NSTimer
属性 并在单元格 willDisplay
/willEndDisplay
.[=14= 时设置 start/stop ]
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()
}
}
}