【问题标题】:Why is my swift code pausing at the loading screen?为什么我的 swift 代码在加载屏幕上暂停?
【发布时间】:2015-05-19 23:45:58
【问题描述】:
if timerRunning == false{
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("counting"), userInfo: nil, repeats: true)
    timerRunning = true
}
while timerLabel.text != "0"{
gameViewStillRunning = false
}
if gameViewStillRunning == false{
    self.performSegueWithIdentifier("segue", sender: nil)
}

这段代码的目的是显示一个倒计时的标签,然后当它到达 0 时,场景应该切换到不同的 ViewController。这段代码没有出现任何错误,但是当我运行它时,程序没有比加载屏幕更进一步。有什么建议吗?

【问题讨论】:

  • “加载屏幕”是指什么屏幕?您是否看到带有您应该在此处更新的标签的屏幕? (timerLabel的那个?)
  • 应该包含更多的代码,你没有在这段代码中减少你的计数器,应该全部显示出来

标签: ios swift uiviewcontroller segue


【解决方案1】:

看起来您正在主线程上运行while 循环,该线程也是负责绘制 UI 的线程。只要该线程卡在您的 while 循环中,它的运行循环就无法继续,也没有机会更新显示或响应用户交互。

此外,如果您查看NSTimer 文档,您可能会注意到scheduledTimerWithTimeInterval 声明它Creates and returns a new NSTimer object and schedules it on the current run loop in the default mode. 该计时器正在调度主线程的运行循环中对您的counting 函数的调用,但由于该线程是卡在你的 while 中永远旋转它永远不会有机会执行,所以它没有机会更新 timerLabel.text

与其在轮询某些条件时尝试使用 while 循环阻止执行,更好的解决方案是允许运行循环继续并在计时器调用您的 counting 函数时做出反应。让您的应用程序对事件(如剩余时间的变化)做出反应,无论它们何时或如何发生,而不是试图控制确切的执行顺序。

【讨论】:

    【解决方案2】:

    问题是这是一个无限循环:

    while timerLabel.text != "0"{
        gameViewStillRunning = false
    }
    

    循环体不会改变timerLabel.text的值,所以条件(第一行的测试)一直失败,循环永远循环——代码和整个应用程序,就在那一点上挂起,永久停止。

    【讨论】:

    • 无限循环总是危险的,也是程序员可能犯的最基本的错误之一。苹果在加利福尼亚州山景城的地址是 One Infinite Loop 是有原因的。
    猜你喜欢
    • 2022-10-18
    • 2017-11-19
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多