UdonSenpai
UdonSenpai

Reputation: 55

Swift- NSTimer crashing app

In Xcode I have this:

import UIKit
import AVFoundation
import Foundation

var position = 0
var gameTimer = NSTimer()

class ViewController: UIViewController {


        @IBAction func button(sender: AnyObject) {

            gameTimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "runTimedCode:", userInfo: nil, repeats: true)

            func runTimedCode() {

                position = Int(arc4random_uniform(11))


            }}}

When I run this app it crashes and returns the error: Thread 1: signal SIGABRT.

I have run the script without the NSTimer and it works perfectly.
I have also run it with and without the colon and it returns the same result.

Upvotes: 1

Views: 605

Answers (2)

Paulw11
Paulw11

Reputation: 114783

You have a couple of issues:

  1. You have defined your runTimedCode function inside your button function rather than as an instance function
  2. You have specified the correct selector signature runTimedCode: (with the colon) but you have not specified the NSTimer argument that will be sent to this function (which is what is indicated by the : in the selector). You want:

import UIKit
import AVFoundation
 import Foundation

var position = 0
var gameTimer : NSTimer?  // Don't assign a value just to keep the compiler happy - if the variable is an optional declare it as such

class ViewController: UIViewController {


    @IBAction func button(sender: AnyObject) {

        self.gameTimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "runTimedCode:", userInfo: nil, repeats: true)

    }

    func runTimedCode(timer:NSTimer) {
            position = Int(arc4random_uniform(11))
    }
}

Upvotes: 0

vadian
vadian

Reputation: 285069

Two issues:

  • Put func runTimedCode() out of the scope of @IBAction button(). Selector / target methods must be on the top level of the class.

  • Either remove the colon of runTimedCode: or declare runTimedCode as runTimedCode(timer: NSTimer). Each colon in a Selector represents one parameter.

Upvotes: 2

Related Questions