从不为NSTimer调用Swift Selector

时间:2016-02-05 20:11:26

标签: swift nstimer

我的Swift类Sentence中有以下实例方法,它调用NSTimer调用类实例方法作为其Selector。当我在没有断点的情况下运行程序时,它会成功到达第一个NSTimer,然后在NSTimer处停止。当我添加断点以查看是否有sentenceDidFinish被调用时,我发现它永远不会,证明它在第一个NSTimer处停止。

class Sentence : NSObject {
   //init() etc.

   func playEvent(eventIndex : Int){
       if (eventIndex < 2){
           let currEvent = self.eventArray[eventIndex]
           currEvent.startEvent()
           let nextIndex = eventIndex + 1
           print("Play Event event id is ", eventIndex)
           NSTimer.scheduledTimerWithTimeInterval(currEvent.duration, target: self, selector: Selector("playEvent:"), userInfo: NSNumber(integer: nextIndex), repeats: false)
       }
       else if (eventIndex==2){
         self.eventArray[eventIndex].startEvent()
         print("Play Event event id is ", eventIndex)
         NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("sentenceDidFinish"), userInfo: nil, repeats: false)
      }
      else{
        //DO Nothing
      }
  }

  func sentenceDidFinish(){
    //foo
    //bar
  }

}

这是完整的.swift文件:

https://gist.github.com/anonymous/e0839eae1d77e1e4b671

1 个答案:

答案 0 :(得分:6)

当您使用计时器调用playEvent:时,传递的参数将是计时器本身,而不是整数。但是在eventIndex的声明中,你表现得好像是整数。

尝试添加如下方法:

func handleTimer(timer: NSTimer) {
    playEvent(timer.userInfo as! Int)
}

然后像这样调用第一个计时器:

NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "handleTimer:", userInfo: NSNumber(integer: nextIndex), repeats: false)

如果as!无法投放到userInfo,强制投射(Int)将会崩溃。更安全,但更详细的看起来像:

func handleTimer(timer: NSTimer) {
    guard let index = timer.userInfo as? Int else { return }
    playEvent(index)
}