Argument of '#selector' does not refer to an '@objc' method, property or initializer

浪尽此生 提交于 2019-12-07 09:22:41

问题


Can anyone tell me why this code gives the error message "Argument of '#selector' does not refer to an '@objc' method, property or initializer"?

timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(updateTimer(until: 3)), userInfo: nil, repeats: true)   

Here's the function:

func updateTimer(until endTime: Int) { 
    counter -= 1
    timeLabel.text = String(counter)
    if counter == endTime {
        step += 1
    }
}

What I have tried:
1. Adding @objc in front of the function.


回答1:


The selector of a target / action method must be declared either without parameter or with one parameter passing the affected object.

In case of a Timer use the userInfo parameter to pass data.

timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(updateTimer(_:)), userInfo: 3, repeats: true)   


func updateTimer(_ timer: Timer) { 
    let endTime = timer.userInfo as! Int
    counter -= 1
    timeLabel.text = String(counter)
    if counter == endTime {
        step += 1
    }
}

If the enclosing class does not inherit form NSObject you have to add the @objc attribute to the action method.



来源:https://stackoverflow.com/questions/44493778/argument-of-selector-does-not-refer-to-an-objc-method-property-or-initial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!