pot*_*ato 2 while-loop ios swift
如何创建一个while循环,每秒检查一次?
也许是这样的:
while (isConditionSatisfied){
// wait for 1 second and than check again
}
Run Code Online (Sandbox Code Playgroud)
编辑:系统bannerViewDidLoadAd随机调用此函数.如果它在不适当的时间调用它(条件不满意 - 我的应用程序正在执行其他动画),我想推迟其实现(只是一个UIView动画),直到满足条件(我的应用程序已完成动画,现在实现应该被执行).我原以为我可以每秒钟检查一下这个状态,但正如你们所说的那样......这是一个坏主意.
像这样使用while循环实际上会创建一个无限循环.你应该使用Timer().
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.loop), userInfo: nil, repeats: true)
Run Code Online (Sandbox Code Playgroud)
然后
@objc
func loop() {
if yourCondition {
// your code here
timer.invalidate()
}
}
Run Code Online (Sandbox Code Playgroud)
确保使用其他变量声明声明计时器,因此一旦满足条件,它就会失效:
var timer: Timer!
Run Code Online (Sandbox Code Playgroud)
带间隔的快速循环
iOS 10
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
if someCondition {
timer.invalidate()
}
}
Run Code Online (Sandbox Code Playgroud)
* withTimeInterval- 秒数