Swift 4:Timer Crashing - 无法识别的选择器发送到实例 [英] Swift 4: Timer Crashing - unrecognized selector sent to instance

查看:176
本文介绍了Swift 4:Timer Crashing - 无法识别的选择器发送到实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调用Timer的一个实例,并为每一秒钟打印已经过了一秒。我正在关注完整的iOs 11&关于Udemy的Swift开发者课程。教师完成了这一点并且他的代码正常运行,但是我的崩溃了。

I'm trying to call an instance of Timer and print "A second has passed" for each second that elapses. I'm following The Complete iOs 11 & Swift Developer Course on Udemy. The instructor does exactly this and his code works, yet mine is crashing.

这是代码:

var timer: Timer! = Timer()

@IBAction func cameraPressed(_ sender: Any) {
    timer.invalidate()
}

func processTimer() {
    print("A second has passed")
}

override func viewDidLoad() {
    super.viewDidLoad()

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: Selector("processTimer"), userInfo: nil, repeats: true)

它应该在运行应用程序时启动计时器,然后在我按下cameraPressed按钮时停止它。但是,它出错了:

It should start the timer upon running the application and then stop it when I press the cameraPressed button. However, it's erroring out with:


无法识别的选择器发送到实例...

unrecognized selector sent to instance...


libc ++ abi.dylib:以NSException类型的未捕获异常终止

libc++abi.dylib: terminating with uncaught exception of type NSException

我是Swift的新手,其他与此类似的StackOverflow问题并没有解决我的问题。我试过改变了计时器!可选定时器?并将Selector(processTimer)更改为#selector(processTimer)并且我仍然没有让它工作。

I'm new to Swift and the other StackOverflow problems that seem similar to this aren't solving my problem. I've tried changed the "Timer!" optional to "Timer?" and changing "Selector("processTimer")" to "#selector(processTimer)" and I'm still not getting it to work.

推荐答案

试试这个。

var timer: Timer! = Timer()

@IBAction func cameraPressed(_ sender: Any) {
    timer.invalidate()
}

@objc func processTimer() {
    print("A second has passed")
}

override func viewDidLoad() {
    super.viewDidLoad()

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(processTimer), userInfo: nil, repeats: true)
}

在Swift 4+中,你需要为选择器方法明确 @objc 。在此之前它曾经是隐含的obj-C。也许教师视频正在运行较旧版本的Swift。

In Swift 4+ you need to have @objc explicity for selector methods. Before that it used to be implicitly obj-C. Maybe the instructor video is running an older version of Swift.

这篇关于Swift 4:Timer Crashing - 无法识别的选择器发送到实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆