如果不在viewWillDisappear中执行此操作,我如何使NSTimer无效/取消? [英] How can I invalidate/deinit a NSTimer without doing it in viewWillDisappear?

查看:195
本文介绍了如果不在viewWillDisappear中执行此操作,我如何使NSTimer无效/取消?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var faderTimer: NSTimer?
override func viewDidLoad() {
    super.viewDidLoad()

    self.faderTimer = NSTimer.scheduledTimerWithTimeInterval(self.fadeTime, target: self, selector: Selector("fadeBackground"), userInfo: nil, repeats: true)
}

我需要使这个计时器无效在控制器离开之前。

I need to invalidate this timer before the controller deinits.

deinit {
    //never gets called
    if let timer = self.faderTimer {
        self.faderTimer!.invalidate()
        self.faderTimer = nil
    }
}

但是,我不能把它粘在deinit()中。似乎我必须在 viewWillDisappear 中使其无效。但是,我不想这样做,因为它会影响背景切换。 (从后台返回不会调用viewWillAppear,所以我必须使用通知来启动计时器,这是一个巨大的痛苦。)我宁愿在viewDidLoad上启动计时器并在deinit()上停止它。

However, I can't stick it in the deinit(). It seems that I have to invalidate it in viewWillDisappear. However, I don't want to do that, because it messes up the background switching. (Returning from background doesn't call viewWillAppear, so I have to use notifications to start the timer, which is a huge pain.) I rather just start the timer on viewDidLoad and stop it on deinit().

推荐答案


我只是在 viewDidLoad 上启动计时器并停止它在 deinit()

I rather just start the timer on viewDidLoad and stop it on deinit()

嗯,你不能。计时器保留您( self ),并将继续这样做,直到它失效。这意味着除非你采取行动使其他地方的计时器无效,否则 deinit 将永远不会被称为并且视图控制器将泄漏(它永远不会出现存在的,以及它所持有的所有记忆以及它所有属性的记忆将继续存在)。你必须找到另一个地方来使计时器无效;这就是它的方式。

Well, you can't. The timer is retaining you (self), and will continue to do so until it is invalidated. This means that unless you take action to invalidate the timer elsewhere, deinit will never be called and the view controller will leak (it will never go out of existence, and all the memory it is holding, along with that of all its properties, will continue to be held). You must find another place to invalidate the timer; that's just the way it is.

如果您不喜欢,则不要使用NSTimer 。请改用GCD和 dispatch_source_t 。这样做的好处是它基于一个块(一个闭包) - 你可以使用弱自我无主自我在块内部以防止自己被保留,因此如果你愿意,你可以在 deinit 中使计时器无效。这正是我创建 GCD的原因基于计时器类,作为NSTimer的替代品。

If you don't like that, then don't use NSTimer. Use GCD and dispatch_source_t instead. This has the advantage that it is based around a block (a closure) - and you can use weak self or unowned self inside the block to prevent yourself from being retained, and thus you can invalidate the timer in deinit if you want to. That is exactly why I have created a GCD-based timer class, as a substitute for NSTimer.

这篇关于如果不在viewWillDisappear中执行此操作,我如何使NSTimer无效/取消?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆