如何锁定异步功能,以便在再次运行之前等待第一次调用完成

时间:2015-10-08 17:31:59

标签: ios swift

我不希望连续多次运行相同的异步函数。我希望函数等到第一次调用函数完成才能再次运行

我尝试将事件取消连接,然后重新连接,但这似乎并不能阻止多次调用该函数

代码:

 func scrollViewDidScroll(scrollView: UIScrollView)
{
 myScrollView.delegate = nil
 myAsync()
 myScrollView.delegate = self
}

我还尝试将代表设置为nil和self在函数内部,但这样做无论如何

1 个答案:

答案 0 :(得分:0)

您可以在调用异步函数时引入Bool属性running并将其设置为true。异步函数完成后,将其设置回false。然后你只在running == false

时调用异步函数
func scrollViewDidScroll(scrollView: UIScrollView) {
    if !running {
        running = true
        myAsync()
    }
}

func myAsync() {
    // do your async stuff
    running = false // this has to be done on the main thread after the async stuff has finished
}