Reputation: 55
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
Reputation: 114783
You have a couple of issues:
runTimedCode
function inside your button
function rather than as an instance functionrunTimedCode:
(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
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