簡體   English   中英

Swift- NSTimer崩潰的應用程序

[英]Swift- NSTimer crashing app

在Xcode中,我有這個:

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))


            }}}

當我運行此應用程序時,它崩潰並返回錯誤: Thread 1: signal SIGABRT.

我已經在沒有NSTimer的情況下運行了腳本,它運行得很好。
我也使用和不使用冒號來運行它,並且返回相同的結果。

兩個問題:

  • func runTimedCode()放在@IBAction button()的范圍@IBAction button() 選擇器/目標方法必須在類的頂層。

  • 或者刪除的結腸runTimedCode:或聲明runTimedCoderunTimedCode(timer: NSTimer) Selector每個冒號代表一個參數。

您有幾個問題:

  1. 您已經在button函數中而不是實例函數中定義了runTimedCode函數
  2. 您已經指定了正確的選擇器簽名runTimedCode:帶有冒號),但是尚未指定將發送到此函數的NSTimer參數(這是選擇器中的:所指示的)。 你要:

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))
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM