Thalatta
Thalatta

Reputation: 4578

Swift: Trying to target Class method as selector for NSTimer

I am trying to use a class method of my class Sentence as the selector for my NSTimer. Here is my method, which incidentally is also the one which makes the NSTimer call :

func playEvent(eventIndex : Int){
    if (eventIndex < 2){
        let currEvent = self.eventArray[eventIndex]
        currEvent?.startEvent()
        let nextIndex = eventIndex + 1
        NSTimer.scheduledTimerWithTimeInterval((currEvent?.duration)!, target: self, selector: "playEvent:sentence:", userInfo: NSNumber(integer: nextIndex), repeats: true)
    }
    else if (eventIndex==2){
        self.eventArray[eventIndex]?.startEvent()
        NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "sentenceDidFinish", userInfo: nil, repeats: true)
    }
    else{
        //do nothing
    }
}

Do I need to write self.playEvent in the selector or is that impossible to do?

Here is the whole class context: https://gist.github.com/ebbnormal/e56b0b6ebedbe4474d01

Upvotes: 0

Views: 753

Answers (1)

Casey
Casey

Reputation: 6701

your question/code is hard to follow, please add the class definition and reword the question.

UPDATE

class SomeClass: NSObject {

    class func someClassMethod() {
        print("called class method")
    }

    func someInstanceMethod() {
        print("called instance method")
    }

    func setupInstanceMethodTimer() {
        NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("someInstanceMethod"), userInfo: nil, repeats: true)
    }

}

// setup timer for class method
NSTimer.scheduledTimerWithTimeInterval(0.4, target: SomeClass.self, selector: Selector("someClassMethod"), userInfo: nil, repeats: true)

// setup timer for instance method
let someInstance = SomeClass()
someInstance.setupInstanceMethodTimer()

Upvotes: 2

Related Questions