0

I'm trying to use an NSTimer to run a function at a certain interval, but every time it runs the program crashes with an exception:

+[Project.Class updateLabel]: unrecognized selector sent to class...
Terminating app due to uncaught exception "NSInvalidArgumentException".

The code is as follows:

class SecondViewController: UIViewController {

// MARK: Properties

override func viewDidLoad() {
    super.viewDidLoad()

    do {
        try updateLabel()
        try startTimer()
    }
    catch{
        self.showAlert()
    }
}

@IBOutlet weak var i2cLabel: UILabel!

// MARK: Actions

func startTimer() throws {
    _ = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateLabel"), userInfo: nil, repeats: true)

}

func showAlert() {
}

func updateLabel() throws {
}
}

If I comment out the NSTimer line, the program compiles and runs just fine.

Note that updateLabel(), the selector function, takes no arguments so calling it as a selector without a colon suffix should work. This seems to be unique to this problem.

K. Standeven
  • 103
  • 1
  • 8

1 Answers1

1

Try update your code to:

override func viewDidLoad() {
    super.viewDidLoad()

    do {
        updateLabel()
        try startTimer()
    }
    catch{
        self.showAlert()
    }
}


// MARK: Actions

func startTimer() throws {
    _ = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateLabel"), userInfo: nil, repeats: true)

}

func showAlert() {
}

func updateLabel() {

}

It seems that: NSTimer don't know call a function throws. So it will crash.

I have tried to find some official or some article describe about it. But sad that I can't find now.

You can reference to this question: Reference

Hope this help!

Community
  • 1
  • 1
vien vu
  • 4,277
  • 2
  • 17
  • 30