gpt4 book ai didi

swift - '#selector' 的参数不引用 '@objc' 方法、属性或初始值设定项

转载 作者:搜寻专家 更新时间:2023-10-31 08:24:55 24 4
gpt4 key购买 nike

谁能告诉我为什么这段代码给出错误消息“'#selector' 的参数不引用'@objc' 方法、属性或初始化程序”?

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。

最佳答案

目标/操作方法的选择器必须在没有参数的情况下声明,或者有一个参数传递受影响的对象。

Timer 的情况下,使用 userInfo 参数传递数据。

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 属性添加到操作方法。

关于swift - '#selector' 的参数不引用 '@objc' 方法、属性或初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44493778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com