使 NSTimer 失效 [英] Invalidating NSTimer

查看:65
本文介绍了使 NSTimer 失效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有 4 个 NSTimers 对象,它们每隔几秒钟就向一个休息 URL 发出请求.

I have 4 NSTimers objects in my app , that make requests to a rest URL every few seconds.

点击一个特定的按钮我想停止计时器以便它停止轮询,点击另一个按钮我想恢复轮询.

On clicking of a particular button I want to stop the timer so that it stops polling and on click of another button I want to resume polling.

我已经为所有计时器尝试了 invalidate 但不起作用.

I have tried invalidate for all timers but does not work.

注意:所有计时器都在不同的类中,我正在尝试使另一个类中的计时器无效任何帮助将不胜感激,谢谢.

NOTE: All timers are in different class and I'm trying to invalidate the timers in another class Any help will be appreciated , thank you.

class NotificationViewController:UIViewController {
    var timer:NSTimer?
    getEvents(){
    if((timer == nil)) {
        timer = NSTimer.scheduledTimerWithTimeInterval(20.0, target: self, selector: Selector("getEvents"), userInfo: nil, repeats: true)
    }
  }
}

在另一堂课中,我通过单击按钮来执行此操作

In another class I'm doing this on click of a button

class Menu:UIViewController {

    @IBAction func buttonTapped(sender: UIButton) {
        self.notify.timer?.invalidate()
        self.notify.timer = nil
    }
}

推荐答案

尝试创建一个单独的 NotificationTimer 类,并像这样在整个项目中使用它的共享对象.

Try to create a separate NotificationTimer class and used its shared object all over the project like this way.

class NotificationTimer: NSObject {

    var timer1: NSTimer?
    var timer2: NSTimer?
    var timer3: NSTimer?
    var timer4: NSTimer?

    static let sharedManager = NotificationTimer()

    func getEvents(){
        print("Fired")
        if (timer1 == nil){
            timer1 = NSTimer.scheduledTimerWithTimeInterval(20.0, target: self, selector: Selector("methodYouWantToCall"), userInfo: nil, repeats: true)
        }
    }    
}

现在像这样在任何 ViewController 中调用这个 timer1 对象.

Now call this timer1 object inside any ViewController like this way.

let notificationTimer = NotificationTimer.sharedManager
notificationTimer.timer1?.invalidate()

或者像这样调用那个方法

Or call that method like this way

NotificationTimer.sharedManager().getEvents()

这篇关于使 NSTimer 失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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