Search code examples
iosswiftnstimer

Define a variable as AnyObject so that it can be changed later to NSTimer--Swift


So, I am trying to make a timer (run correctly) in swift.

func doSomething(){
    println("Did something")
}
@IBActionFunc createTimer: AnyObject{
    var timer = NSTimer(timeInterval: 0.2, target: self, selector: "doSomething", userInfo: nil, repeats: true)
}
@IBActionFunc stopTimer: AnyObject{
    timer.invalidate()
}

Other option:

var timer:AnyObject = AnyObject
func doSomething(){
    println("Did something")
}
@IBActionFunc createTimer: AnyObject{
    timer = NSTimer(timeInterval: 0.2, target: self, selector: "doSomething", userInfo: nil, repeats: true)
}
@IBActionFunc stopTimer: AnyObject{
    timer.invalidate()
}

I am not sure if this should actually work. From my tests, it does not because "timer" is defined as a local variable (?), so it cannot be accessed from other functions (?). To try to fix this, I first defined "var timer" to AnyObject, so that it can be redefined as anything later. Sadly, I get crazy errors and no's. Should I even need to do this second thing, or should the first one work? Thanks in advance!


Solution

  • You're right in that you currently have a local variable, so you can't reference it in other functions. You need an instance variable, such as:

    class MyClass {
        var timer: NSTimer
    
        ...
    
        @IBActionFunc createTimer: AnyObject{
            timer = NSTimer(timeInterval: 0.2, target: self, selector: "doSomething", userInfo: nil, repeats: true)
        }
    
        ...