在 Swift 中使用 NSTimer 时,无法识别的选择器发送到 class; NSInvalidArgumentException 异常

Unrecognized selector sent to class when using NSTimer in Swift; NSInvalidArgumentException

我正在尝试使用 NSTimer 在特定时间间隔 运行 一个函数,但每次 运行 程序都会崩溃并出现异常:

+[Project.Class updateLabel]: unrecognized selector sent to class...
Terminating app due to uncaught exception "NSInvalidArgumentException".

代码如下:

class SecondViewController: UIViewController {

// MARK: Properties

override func viewDidLoad() {
    super.viewDidLoad()

    do {
        try updateLabel()
        try startTimer()
    }
    catch{
        self.showAlert()
    }
}

@IBOutlet weak var i2cLabel: UILabel!

// MARK: Actions

func startTimer() throws {
    _ = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateLabel"), userInfo: nil, repeats: true)

}

func showAlert() {
}

func updateLabel() throws {
}
}

如果我注释掉 NSTimer 行,程序会编译并且 运行s 就好了。

请注意,选择器函数 updateLabel() 不带任何参数,因此将其作为不带冒号后缀的选择器调用应该可行。这似乎是这个问题所特有的。

尝试将您的代码更新为:

override func viewDidLoad() {
    super.viewDidLoad()

    do {
        updateLabel()
        try startTimer()
    }
    catch{
        self.showAlert()
    }
}


// MARK: Actions

func startTimer() throws {
    _ = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateLabel"), userInfo: nil, repeats: true)

}

func showAlert() {
}

func updateLabel() {

}

似乎:NSTimer不知道调用函数throws。所以它会崩溃。

我试图找到一些官方或一些文章描述它。可惜现在找不到了

你可以参考这个问题:

希望对您有所帮助!