【问题标题】:while loop not executing with timerwhile 循环不与计时器一起执行
【发布时间】:2018-04-01 00:58:15
【问题描述】:

我对 Swift 很陌生,现在已经练习了大约一周。我已经声明了一个定时器,我用viewDidLoad() 调用定时器的函数,定时器#selector 指向goldPerSec,该函数是一个简单的while 循环,但它并没有按应有的每秒执行一次。

这是我的代码:

var timer = Timer()

override func viewDidLoad() {
    super.viewDidLoad()
    counter()
}

func counter() {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.goldPerSec), userInfo: nil, repeats: true)
}

@objc func goldPerSec() {
    while (totalOwned >= 1) {
        Gold += (minerOwned * 1)
        goldLabel.text = "\(Gold)"
    }
}

【问题讨论】:

    标签: ios swift timer


    【解决方案1】:

    goldPerSec 中的 while 循环永远运行,阻止任何其他代码在主队列上运行,包括计时器。

    while 循环更改为if 语句。

    @objc func goldPerSec() {
        if totalOwned >= 1 {
            Gold += minerOwned * 1
            goldLabel.text = "\(Gold)"
        }
    }
    

    现在,这将允许从计时器每秒调用一次 goldPerSec,并且还允许您的用户界面的其余部分工作。

    附带说明,变量名称应以小写字母开头,因此 Gold 应命名为 gold

    【讨论】:

    • 作为一个 3 年的后端 PHP 开发人员,我很尴尬,我无法弄清楚这一点,这 110% 有道理。非常感谢。另外,在 if 和 while 的条件下,可以用括号写 if (totalOwned...) 吗?这是我最熟悉的,当然我会在整个代码中这样做以保持一致。
    • Swift 中不需要括号。
    • 如果我使用括号会遇到任何问题吗?我个人觉得使用它们时更有条理并且更容易阅读。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    相关资源
    最近更新 更多