swift - 发送到类的静态函数无法识别的选择器
问题描述
我有一个带有每 3 秒触发一次的计时器的简单 ViewController,当我使用以下代码时,它按预期工作。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var myTimer = MyTimer()
myTimer.triggerTimer()
}
}
class MyTimer: NSObject {
var timer: Timer?
func triggerTimer() {
DispatchQueue.main.async {
if self.timer == nil {
self.timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.timeout), userInfo: nil, repeats: true)
}
}
}
@objc func timeout() {
print("timeout")
}
}
但是当我更改timer
andtriggerTimer()
时static
,就会发生错误。这是调用错误的代码:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
MyTimer.triggerTimer()
}
}
class MyTimer: NSObject {
static var timer: Timer?
static func triggerTimer() {
DispatchQueue.main.async {
if self.timer == nil {
self.timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.timeout), userInfo: nil, repeats: true)
}
}
}
@objc func timeout() {
print("timeout")
}
}
错误是:
unrecognized selector sent to class 0x10906b338'
*** First throw call stack:
(
0 CoreFoundation 0x000000010a2dc1e6 __exceptionPreprocess + 294
1 libobjc.A.dylib 0x0000000109971031 objc_exception_throw + 48
2 CoreFoundation 0x000000010a35d6c4 +[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x000000010a25e898 ___forwarding___ + 1432
4 CoreFoundation 0x000000010a25e278 _CF_forwarding_prep_0 + 120
5 Foundation 0x00000001093db4dd __NSFireTimer + 83
6 CoreFoundation 0x000000010a26be64 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
7 CoreFoundation 0x000000010a26ba52 __CFRunLoopDoTimer + 1026
8 CoreFoundation 0x000000010a26b60a __CFRunLoopDoTimers + 266
9 CoreFoundation 0x000000010a262e4c __CFRunLoopRun + 2252
10 CoreFoundation 0x000000010a26230b CFRunLoopRunSpecific + 635
11 GraphicsServices 0x000000010fe57a73 GSEventRunModal + 62
12 UIKit 0x000000010a7590b7 UIApplicationMain + 159
13 StaticProject 0x0000000109067b27 main + 55
14 libdyld.dylib 0x000000010e747955 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
我通过网站搜索并看到一些类似的问题,但我找不到正在讨论的答案。谁能给我一些提示?谢谢你。
解决方案
由于现在timer: Timer?
andtriggerTimer()
是静态的,您还需要将timeout
方法设为静态,对代码进行以下更改......
@objc static func timeout() {
print("timeout")
}
推荐阅读
- entity-framework - 过滤器在我的 ASP.NET Core 存储库中不起作用
- windows - 如何检测从哪里调用协议
- amazon-web-services - 带有非常简单 SSL 插件的官方 Lightsail SSL 对 Debian 实例来说是错误的
- java - 如何避免访问二维数组中的无效位置?
- r - R - 在包含字符串、NA 和组的数据框中提取最大/最小值行
- git - 使用 git add 添加所有项目,但图像
- reactjs - 如果用户尚未确认电子邮件,则反应路线
- javascript - 在 Liquid 中的集合页面中,每隔 n 次迭代渲染一次
- laravel - 如果未找到结果,Laravel 查询默认为 0
- java - 在java中创建树的所有可能的子树