cocoa - How do I run a function with a parameter every 5 seconds in Swift? -
i want execute following function every 5 seconds. have seen other answers related questions use nstimer.scheduledtimerwithtimeinterval works functions without arguments.
the function:
func sayhello(name: string) {     println("hey \(name)!") }   this code tried:
var timer = nstimer.scheduledtimerwithtimeinterval(5.0, target: self, selector: selector("sayhello(\(name))"), userinfo: nil, repeats: true)   but crashes app error:
terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[jake.swiftapp sayhello(jake)]: unrecognized selector sent instance 0x7fcd515640a0'   how run function 1 input parameter?
the problem is, when set selector nstimer fire, have pass name of method.
right now, you're dynamically building string , trying point method called:
"sayhello(jake)"   which doesn't exist. in fact, in can't exist. doesn't make sense.
the sayhello() fun if you're adding selector string:
"sayhello:"   but fixing still problems.  nstimer's target can take 0 or 1 arguments.  , if take argument, expects argument nstimer.  when nstimer's fire , call target, pass parameter.
so, need setup our method this:
func sayhello(timer: nstimer) {     // stuff }   and pass selector("sayhello:") our selector argument.
in order pass sort of arguments in, have package them nstimer's userinfo property, of type anyobject?.  then, within method our timer calls, can access property.
class exampleclass {     var timer: nstimer?      var username: string? {         set {             self.timer?.userinfo = newvalue         }         {             return self.timer?.userinfo as? string         }     }      func timertick(timer: nstimer) {         if let username = timer.userinfo as? string {             self.sayhello(username)         }     }      func sayhello(username: string) {         println("hello " + username + "!")     }      func starttimer(#interval: nstimeinterval = 5.0, username: string? = nil) {         self.timer = nstimer.scheduledtimerwithtimeinterval(interval,              target: self,              selector: selector("timertick:"),              userinfo: username,              repeats: true         )     } }   from here, time want change name timer carrying around, can do:
self.username = "jake"      
Comments
Post a Comment