Search code examples
iosswiftgrand-central-dispatch

Leaving dispatchGroup with DEFER cause a crash


I have an rest Api async method, so use dispatch group:

let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
Task.do { result in
   defer { dispatchGroup.leave() }
    //...
}

this make a crash Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

But

let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
Task.do { result in
    //...
    dispatchGroup.leave()
}

don't crash. Why?


Solution

  • Point 1 is : defer is called when scope of your function ends ...

    Point 2 is : dispatchGroup enter should be equal to leaves otherwise your application will crash