Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a static method from NSTimer. Is it possible?

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?

like image 790
Luke Bartolomeo Avatar asked Mar 27 '15 19:03

Luke Bartolomeo


1 Answers

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()
like image 146
Vatsal Manot Avatar answered Oct 06 '22 01:10

Vatsal Manot