为什么我的 swift 代码在加载屏幕上暂停?
Why is my swift code pausing at the loading screen?
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。这段代码没有任何错误,但是当我 运行 它时,程序不会比加载屏幕更进一步。有什么建议吗?
问题是这是一个无限循环:
while timerLabel.text != "0"{
gameViewStillRunning = false
}
循环体不会改变 timerLabel.text
的值,所以条件(第一行的测试)一直失败,循环就一直循环下去——还有代码,等等整个应用程序,就在那一点挂起,永久停止。
看起来您正在 运行 在主线程上执行 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
函数。让您的应用程序对事件(如剩余时间变化)做出反应,而不管它们何时或如何发生,而不是试图控制执行的确切顺序。
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。这段代码没有任何错误,但是当我 运行 它时,程序不会比加载屏幕更进一步。有什么建议吗?
问题是这是一个无限循环:
while timerLabel.text != "0"{
gameViewStillRunning = false
}
循环体不会改变 timerLabel.text
的值,所以条件(第一行的测试)一直失败,循环就一直循环下去——还有代码,等等整个应用程序,就在那一点挂起,永久停止。
看起来您正在 运行 在主线程上执行 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
函数。让您的应用程序对事件(如剩余时间变化)做出反应,而不管它们何时或如何发生,而不是试图控制执行的确切顺序。