定时器,#selector解释
Timer, #selector explanation
我需要一个定时器所以我使用了这个代码:
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(generalKnowledge.method), userInfo: nil, repeats: true)
可是我看不懂#selector
。试了很多次都不行。
selector() 是您添加希望它在您设置的每次 timeInterval 中调用的函数的地方。在您的示例中,它是每秒。
请记住,在 Swift 4 及更高版本中,如果您想在选择器中调用函数,则需要在函数前添加 @objc
:
@objc func handleEverySecond() {
print("Hello world!")
}
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(handleEverySecond), userInfo: nil, repeats: true)
选择器本质上是发送给对象的消息。它主要用于 objective-C 并且 Swift 试图摆脱它。但是,仍然有一些 objective-C API 使用它,包括计时器。
这就是选择器必须标记为 @objc
的原因,因为它需要公开才能被看到。
因此,当您将选择器传递给计时器时,您就是在告诉它在触发时将此消息发送到 class。
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(action), userInfo: nil, repeats: true)
@objc func action() {
print("timer fired")
}
此外,请务必记住,您需要在函数范围之外保留对计时器的引用。
我需要一个定时器所以我使用了这个代码:
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(generalKnowledge.method), userInfo: nil, repeats: true)
可是我看不懂#selector
。试了很多次都不行。
selector() 是您添加希望它在您设置的每次 timeInterval 中调用的函数的地方。在您的示例中,它是每秒。
请记住,在 Swift 4 及更高版本中,如果您想在选择器中调用函数,则需要在函数前添加 @objc
:
@objc func handleEverySecond() {
print("Hello world!")
}
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(handleEverySecond), userInfo: nil, repeats: true)
选择器本质上是发送给对象的消息。它主要用于 objective-C 并且 Swift 试图摆脱它。但是,仍然有一些 objective-C API 使用它,包括计时器。
这就是选择器必须标记为 @objc
的原因,因为它需要公开才能被看到。
因此,当您将选择器传递给计时器时,您就是在告诉它在触发时将此消息发送到 class。
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(action), userInfo: nil, repeats: true)
@objc func action() {
print("timer fired")
}
此外,请务必记住,您需要在函数范围之外保留对计时器的引用。