简体   繁体   English

SWIFT-防止同时调用同一函数

[英]SWIFT - prevent same function from being called concurrently

I have an application where the main UI waits for some calculation to be done before updating. 我有一个应用程序,其中主UI在更新之前等待一些计算。 The whole application depends solely on the user's connectivity to wifi as we are making any api calls to calculate the data. 整个应用程序仅取决于用户与wifi的连接,因为我们正在进行任何api调用来计算数据。 Sometimes, in RARE conditions, the function that runs everything gets executed twice... causing the updated UI to display invalid data. 有时,在RARE条件下,运行所有内容的函数都会执行两次……导致更新后的UI显示无效数据。

What are some ways i can prevent this from happening. 有什么方法可以防止这种情况发生? Sorry i'm not showing code because it'll be easier to explain the concept. 抱歉,我没有显示代码,因为它更容易解释这个概念。

Edit: To reproduce this error, this is what i do. 编辑:要重现此错误,这就是我所做的。 Pseudocode below 下面的伪代码

override func viewDidLoad() {
    mainCall()
}


override func viewWillAppear(_ animated: Bool) {
    mainCall()
}


func executeOne(){
    callA(){}
    callB(){}
    etc...
}

You can use a bool variable to indicate whether an API call is already in progress or not and only trigger an API call in case another one is not in progress. 您可以使用bool变量来指示API调用是否已经在进行中,并且仅在未进行另一个API调用时才触发。

class YourClass {
    var apiCallIsInProgress = false

    func apiCall(){
        if !apiCallIsInProgress {
            // doApiCall is the function actually implementing the API call and returning the result through a completion handler
            doApiCall(completion: {
                apiCallIsInProgress = false
            }
        } else {
            apiCallIsInProgress = true
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM