努力理解@objc方法swift 4

时间:2017-11-29 06:25:01

标签: swift timer

    func updateTimer() {
            counter = counter - 1
        if (counter > 0) {
            countDown.text = String(counter)
        } else if (counter == 0) {
            performSegue(withIdentifier: "testComplete", sender: self)
        }
    }

    Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(("updateTimer")) , userInfo: nil, repeats: false)

我收到错误“#selector'的参数'没有引用'@objc'方法,属性或初始化程序”

4 个答案:

答案 0 :(得分:1)

如果类没有从NSObject继承,那么你必须将@objc属性添加到action方法中。

就像:

@objc func updateTimer() {
        counter = counter - 1
    if (counter > 0) {
        countDown.text = String(counter)
    } else if (counter == 0) {
        performSegue(withIdentifier: "testComplete", sender: self)
    }
}

Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer()) , userInfo: nil, repeats: false)

同时使用#selector(updateTimer())代替#selector(("updateTimer")).

答案 1 :(得分:1)

对您的代码进行了一些更改:

@objc func updateTimer() {
       ...
    }

#selector(updateTimer) // swift 4

答案 2 :(得分:0)

而不是#selector(("updateTimer"))

使用下面的代码

 #selector(self.updateTimer())

#selector(updateTimer)

,您的代码将是

func updateTimer() {
        counter = counter - 1
    if (counter > 0) {
        countDown.text = String(counter)
    } else if (counter == 0) {
        performSegue(withIdentifier: "testComplete", sender: self)
    }
}

Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateTimer) , userInfo: nil, repeats: false)

希望这会对你有所帮助

答案 3 :(得分:0)

这样做:

//Change ClassName to the name of the class
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ClassName.updateTimer), userInfo: nil, repeats: false)