Timer.scheduledTimer不执行选择器功能

时间:2017-03-17 21:28:20

标签: swift nstimer

我创建了一个应用来检查整数是否为素数。它工作正常,但我想添加一个计时器来计算一些更大的素数计算所需的时间。我创建了一个计时器变量,但Timer.scheduledTimer不执行addSecond函数。我究竟做错了什么?感谢

class ViewController: UIViewController {     
    var number = 0.0       
    var timer = Timer()      
    var time = 0

    func addSecond() {          
        time += 1           
    }

    @IBOutlet weak var txtNumber: UITextField!       
    @IBOutlet weak var lblOutput: UILabel!        
    @IBAction func btnCalculate(_ sender: Any) {       
        print("calculating")          
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.addSecond), userInfo: nil, repeats: true)          
        var i = 1
        var divs = 0            

        number = Double(txtNumber.text!)!

        while i <= Int(number)/2 {

            if number.truncatingRemainder(dividingBy: Double(i)) == 0 {

                divs += 1

            }

            i += 1
        }

        if divs > 1 {

            lblOutput.isHidden = false
            lblOutput.text = String(number) + " is not prime"
            timer.invalidate()

        } else {

            lblOutput.isHidden = false
            lblOutput.text = String(number) + " is prime. It took " + String(time) + " seconds to calculate it"
            timer.invalidate()

        }


}

0 个答案:

没有答案