用于从我的Swift应用程序中的NSTimer调用函数的无法识别的选择器

时间:2015-07-26 14:07:50

标签: ios swift nstimer

我应该如何在swift中声明一个函数,以便我可以使用NSTimer。我目前收到的错误是:

'-[MyClass.MyViewController displayOfflineTimerMessage]: unrecognized selector

我尝试在我的函数前添加@objc和dynamic,但都没有工作。

   func sendOfflineSystemMessageIfNeccesary(username:String) {

        var debounceTimer = offlineNotificationDebounceList["username"];
        if let timer = debounceTimer {
            //todo: log warning message since we should never get here
            timer.invalidate()
        }

        debounceTimer = NSTimer(timeInterval: debounceTimeInSeconds, target: self, selector: Selector("displayOfflineTimerMessage"), userInfo: username, repeats: false)
        NSRunLoop.currentRunLoop().addTimer(debounceTimer!, forMode: "NSDefaultRunLoopMode")

    }

    @objc func displayOfflineTimerMessage(timer:NSTimer)
    {
        if let username:String = timer.userInfo as? String {
            offlineNotificationDebounceList.removeValueForKey(username)
            sendConnectionMessage(username, msg: username + " has left")
        }

    }

1 个答案:

答案 0 :(得分:2)

您可以将该行用作

debounceTimer = NSTimer(timeInterval: debounceTimeInSeconds, target: self, selector: "displayOfflineTimerMessage:", userInfo: username, repeats: false)