如何在Swift中将@selector()用于NSTimer和其他方法?
大家好!我是Swift新手,正在尝试理解选择器。我有Objective-C的经验,在那里我经常使用@selector()将方法传递给定时器或事件处理器。例如,我想创建一个简单的定时器,每秒调用一个方法。以下是我的Swift代码:
```swift
import UIKit
class ViewController: UIViewController {
var timer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
// 尝试创建定时器,但不知道如何正确编写选择器
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
func updateTimer() {
print("定时器触发了!")
}
}
```
但Xcode报错:"Argument of '#selector' refers to instance method 'updateTimer()' that is not exposed to Objective-C"。我不明白这是什么意思。在Objective-C中,我只需写@selector(updateTimer)就能工作。为什么