Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如果我在代码中添加此函数,NSTimer会停止,为什么?_Ios_Loops_Swift - Fatal编程技术网

Ios 如果我在代码中添加此函数,NSTimer会停止,为什么?

Ios 如果我在代码中添加此函数,NSTimer会停止,为什么?,ios,loops,swift,Ios,Loops,Swift,有2个Arrays。第一个包含我要在UILabel上显示的Strings。第二个包含他们在UILabel上的等待时间 let items = ["stone","spoon","brush","ball","car"] let durations = [3,4,1,3,2] 和两个变量s,用于指定哪一个正在运行 var currentItem = 0 var currentDuration = 0 这是一个计时器系统: var timer = NSTimer() var seconds =

有2个
Array
s。第一个包含我要在
UILabel
上显示的
String
s。第二个包含他们在
UILabel
上的等待时间

let items = ["stone","spoon","brush","ball","car"]
let durations = [3,4,1,3,2]
和两个
变量
s,用于指定哪一个正在运行

var currentItem = 0
var currentDuration = 0
这是一个计时器系统:

var timer = NSTimer()
var seconds = 0

    func addSeconds () {seconds++}
    func setup () {
        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "addSeconds", userInfo: nil, repeats: true)
    }
最后,这就是循环。回答:哪个
数组
项在
ui标签上停留了多少秒
问题

func flow () {
        while seconds <= durations[currentDuration] {
            myScreen.text = items[currentItem]
            if seconds == durations[currentDuration]{
                seconds == 0
                currentItem++
                currentDuration++
            }
        }
如果我改变这一点:

func addSeconds () {seconds++}
为此:

func addSeconds () {seconds++ ; flow () }

对于设置循环,什么都不会发生。即使是NSTimer,它也会在1秒停止。

因为流方法有一个while循环,它永远不会退出并阻塞主线程,所以计时器永远不会启动

不要使用while循环。使用计时器触发的方法更新UI

因此:


您应该使用NSTimeInterval来计算经过的时间,但是如果我没有包含
flow()
函数,并且在
addSeconds()
函数中说
println(seconds)
,则没有任何问题,它正确地说秒。这就是您的想法。不要说
var timer=NSTimer()
。只需说
var timer:NSTimer。你的版本创建了一个未使用的对象。@LeonardoSavioDabus好的,我已经更正了,但是你能解释一下区别吗?我没那么有经验。
func addSeconds () {seconds++ ; flow () }
func addSeconds () {
    seconds++

    myScreen.text = items[currentItem]

    if seconds == durations[currentDuration] {
        seconds == 0
        currentItem++
        currentDuration++
    }
}