Swift Selector is never called for NSTimer -


i have following instance method in swift class sentence makes call nstimer calls class instance method selector. when run program without breakpoints, gets first nstimer stalls @ nstimer. when add breakpoint see if sentencedidfinish ever called, see never is, proving stops @ first 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 ", 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 ", eventindex)          nstimer.scheduledtimerwithtimeinterval(0.4, target: self, selector: selector("sentencedidfinish"), userinfo: nil, repeats: false)       }       else{         //do nothing       }   }    func sentencedidfinish(){     //foo     //bar   }  } 

here full .swift file:

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

when call playevent: timer, argument passed timer itself, not integer. in declaration eventindex acting if integer.

try adding method this:

func handletimer(timer: nstimer) {     playevent(timer.userinfo as! int) } 

then call first timer this:

nstimer.scheduledtimerwithtimeinterval(0.4, target: self, selector: "handletimer:", userinfo: nsnumber(integer: nextindex), repeats: false) 

the forced casting (as!) crash if userinfo isn't castable int. safer, more verbose like:

func handletimer(timer: nstimer) {     guard let index = timer.userinfo as? int else { return }     playevent(index) } 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -