Is it allowed to call a static method from an NSTimer? The compiler will not allow this, complaining with the cryptic "Extra argument 'selector' in call.
struct MyStruct {
static func startTimer() {
NSTimer.scheduledTimerWithTimeInterval(1.0, target: MyStruct.self, selector: "doStuff", userInfo: nil, repeats: true)
}
static func doStuff() {
println("Doin' it.")
}
}
MyStruct.startTimer()
But of course, this works fine...
class MyClass {
func startTimer() {
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "doStuff", userInfo: nil, repeats: true)
}
func doStuff() {
println("Doin' it.")
}
}
var instanceOfClass = MyClass()
instanceOfClass.startTimer()
Do I just have the syntax wrong, or is it not allowed?
NSTimer
utilizes the Objective-C runtime in order to dynamically invoke methods. When declare a struct
, you are using the Swift runtime, therefore it is not possible for NSTimer
to cooperate. Structures differ from classes, and you can read more about them here.
Also, a static
function is the equivalent of a class method in Objective-C, so if that was your original objective then the following should suffice:
class MyClass: NSObject {
class func startTimer() {
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "doStuff", userInfo: nil, repeats: true)
}
class func doStuff() {
println("Doin' it.")
}
}
MyClass.startTimer()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With