问题描述
谁能告诉我为什么此代码给出错误消息'#selector' 的参数不引用'@objc' 方法、属性或初始值设定项"?
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)
函数如下:
func updateTimer(until endTime: Int) {
counter -= 1
timeLabel.text = String(counter)
if counter == endTime {
step += 1
}
}
我尝试过的:
1.在函数前添加@objc.
What I have tried:
1. Adding @objc in front of the function.
推荐答案
目标/动作方法的选择器必须声明为不带参数或只有一个参数传递受影响的对象.
The selector of a target / action method must be declared either without parameter or with one parameter passing the affected object.
如果是 Timer
,请使用 userInfo
参数来传递数据.
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
}
}
如果封闭类不继承表单 NSObject
,则必须将 @objc
属性添加到操作方法中.
If the enclosing class does not inherit form NSObject
you have to add the @objc
attribute to the action method.
这篇关于“#selector"的参数不引用“@objc"方法、属性或初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!