Search code examples
swiftnstimer

NSTimer hangs program after firing


I am creating a timer inside my ViewController. After it fires once, the program ceases to respond to any further UI events.

I create the timer inside of ViewDidLoad() with:

NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "initTimerFired", userInfo: nil, repeats: false)

with timer function (defined as method of ViewController):

func initTimerFired(){

    println("Timer fired")
}

It successfully fires, but thereafter the program hangs and does not respond to UI events. If I set repeat = true then it runs a couple of times before quitting with EXC_BAD_ACCESS.

I have looked at many different answers and examples, and I can't see what I am doing wrong.

I am running this on an iOS simulator, using xcode 6.1.

Here is an update. Thanks to the suggestions and code provided in the first answer, I have something working. However, my code, which looks to me to be the same, does not work. In order to implement things within the context of a larger project, I want to know how to avoid the errors I am seeing. For instance, this works:

class ViewController: UIViewController {

    @IBOutlet weak var strConsole: UILabel!
    override func viewDidLoad() {

        super.viewDidLoad()
        initTaskManager()

    }

    func initTaskManager(){
        let taskManager = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateTask", userInfo: nil, repeats: true)
    }

    func updateTask(){

        self.strConsole.text = "\(strConsole.text!)Abc"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


}

But this version does not. Only the function names have changed!:

class ViewController: UIViewController {

    @IBOutlet weak var strConsole: UILabel!
    override func viewDidLoad() {

        super.viewDidLoad()
        initTimer()

    }

    func initTimer(){
        let timer1 = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "initTimerFired", userInfo: nil, repeats: true)
    }

    func initTimerFired(){

        self.strConsole.text = "\(strConsole.text!)Abc"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


}

Solution

  • Do not use: initTimerFired, change to something else like: handleTimer,

    init as a prefix of the function name may confuse Xcode

    See here: https://developer.apple.com/library/ios/documentation/swift/conceptual/buildingcocoaapps/InteractingWithObjective-CAPIs.html