Search code examples
arraysswiftgrand-central-dispatch

Leaving DispatchGroup causes my code to crash


I've got the following function but it keeps crashing on the dispatchGroup.leave() statement and I don't understand why. Based on what I found online every dispatchGroup.leave() must be associated with a dispatchGroup.enter() which I believe is the case for my function.

self.kycRecords only contains 1 element (for now) btw.

 @IBAction func checkCustomerList(_ sender: Any) {
        let dispatchGroup = DispatchGroup()

        for kycRecord in self.kycRecords {
            dispatchGroup.enter()
            ApiManager.sharedInstance.postUserToArtemis(kycRecord) {(response, error) in
                dispatchGroup.leave()
                if error != nil {
                    kycRecord.kycStatus = "failed"
                } else {
                    if response == true {
                        kycRecord.kycStatus = "passed"
                    } else {
                        kycRecord.kycStatus = "failed"
                    }
                }
            }
        }

        dispatchGroup.notify(queue: DispatchQueue.main, execute: {
            print("done")
            self.writeOutput()
        })
    }

It crashes with the message:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP,subcode=0x0)

enter image description here


Solution

  • You can check number of count entered in group before leaving from any group by below Patch Work

    let count = self.groupExecuting.debugDescription.components(separatedBy: ",").filter({$0.contains("count")}).first!.components(separatedBy: CharacterSet.decimalDigits.inverted).filter({Int($0) != nil})