【问题标题】:Does not implement methodSignatureForSelector and unrecognized selector when using Timer使用 Timer 时不实现 methodSignatureForSelector 和无法识别的选择器
【发布时间】:2019-04-07 18:15:25
【问题描述】:

这里我有一个简单的类,它每秒打印几次“测试”:

import Foundation

class TestClass {

    static var count = 0
    static var timer = Timer()

    init() {
        TestClass.start()
    }

    static func start() {
        TestClass.timer = Timer.scheduledTimer(timeInterval: 1.0/5.0, target: self, selector: #selector(printTest), userInfo: nil, repeats: true)
    }

    @objc func printTest() {
        print(count)
        count += 1
    }
}

我将函数 start 设为变量 timer static 以便稍后我可以从另一个类启动和停止计时器

在我的主 ViewController 文件中,我只需创建一个新的 TestClass 并说:

let _ = TestClass()

然后我尝试通过以下方式停止和启动计时器:

if /*something*/ {
    TestClass.timer.invalidate()
}

if /*something else*/ {
    TestClass.start()
}

但是,当我运行项目时,我在控制台中收到多个错误:

NSForwarding: warning: object 0x10eaab580 of class 'DeleteMe.TestClass' does not implement methodSignatureForSelector: -- trouble ahead

Unrecognized selector +[DeleteMe.TestClass printTest]

我必须在课堂上修改什么来解决错误吗?

【问题讨论】:

    标签: swift timer nstimer


    【解决方案1】:

    问题在于startstatic 方法,所以self 是类,而不是实例。这意味着printTest 也需要是static

    但为什么这些是静态的?为什么要创建实例只是为了调用静态start 方法?

    去掉init,直接使用TestClass.start()

    或者使一切都成为适当的实例属性和实例方法。然后,您可以创建单独的 TestClass 实例,每个实例都有自己的计时器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多