简体   繁体   English

NSTimer不要在选择器中调用方法

[英]NSTimer don't call the method in selector

Hello 你好

I'm trying to execute a task in background because I need to while the application is running being pulling data from the server. 我正在尝试在后台执行任务,因为我需要在应用程序运行时从服务器提取数据。 I write the code in the AppDelegate.swift, this is the code that i wrote: 我在AppDelegate.swift中编写代码,这是我编写的代码:

    class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {

        var window: UIWindow?
        let manager = AppManager.manager
        var timer: NSTimer? = nil

        func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
            // Override point for customization after application launch.
            self.timer = NSTimer(timeInterval: 1.0, target: self, selector: "UpdateDeviceData:", userInfo: nil, repeats: true)
           return true
         }                                                                                                           
         func UpdateDeviceData(timer:NSTimer) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
               print("do some background task")

               dispatch_async(dispatch_get_main_queue(), { () -> Void in
                  print("update some UI")

            })
        })
    }

}

I put a breakpoint in the line "print" and it never being executed. 我在“打印”行中放置了一个断点,但它从未执行过。

Please any idea about what could be the problem? 请知道可能是什么问题吗?

Note: I'm using Xcode 7 beta and Swift 注意:我正在使用Xcode 7 beta和Swift

You need to schedule the timer on a run loop - you're just assigning it to a variable. 您需要在运行循环上安排计时器-您只是将其分配给变量。 Try using the class method + scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: - 尝试使用类方法+ scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: -

so 所以

NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "UpdateDeviceData:", userInfo: nil, repeats: true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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