How to utilize NSLock to prevent a function from firing twice?

后端 未结 2 1997
悲&欢浪女
悲&欢浪女 2020-12-31 18:43

I current have a set of asynchronous functions that are both called in the viewDidLoad(). At the end of each function is a bool that is set from false to true u

2条回答
  •  别那么骄傲
    2020-12-31 19:36

    Another approach using DispatchGroup. More simple, imho.

    class ViewController: UIViewController {
    
        let group = DispatchGroup()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            group.enter()
            functionOne()
    
            group.enter()
            functionTwo()
    
            group.notify(queue: .global(qos: .default), execute: { [weak self] in
                self?.functionThree()
            })
        }
    
        func functionOne() {
            //async stuff
    
            group.leave()
        }
    
        func functionTwo() {
            //async stuff
    
            group.leave()
        }
    
        func functionThree() {
            //stuff
        }
    }
    

提交回复
热议问题