我正在使用分派(dispatch)组来获取数据字符串。这是一段代码,我不确定为什么会在这段代码中得到 Unbalanced call to dispatch_group_leave()
。
var queue = DispatchQueue(label: "extractStringQueue", attributes: .concurrent)
queue.async {
let m_group = DispatchGroup()
let weeks = self.weekDataArray
for week in weeks {
for day in week.dayDataArray {
m_group.enter()
day.processStringData(dataName, completionHandler: { (data, response, error) in
if true {
// Process
m_group.leave()
}
})
}
}
m_group.notify(queue: queue, execute: {
// CompletionHandler
})
}
最佳答案
两个可能的问题:
问题 1:
processStringData
函数可能会多次调用其 completionHandler
,从而导致多次调用 m_group.leave()
。 m_group.leave()
的次数应始终等于 m_group.enter()
。如果您尝试 m_group.leave()
的次数超过您进入组的次数,您将收到此错误。
问题 2:
m_group.enter()
day.processStringData(dataName, completionHandler: { (data, response, error) in
if true {
// Process
m_group.leave()
}
})
您的代码仅在 completionHandler 返回 true 时才离开该组,因此如果它返回 false,您将永远不会离开该组。这将导致 m_group.notify
永远不会触发,即使一旦完成 block 返回 false 并不必要地永远阻塞线程。
你应该做的是
m_group.enter()
day.processStringData(dataName, completionHandler: { (data, response, error) in
if true {
// Process
}
m_group.leave()
})
问题 3:
确保 processStringData 在执行完成 block 之前没有改变线程。切换回主线程并执行完成 block 是一种常见的做法。使用不同的线程进入 dispatch_group
并试图从完全不同的线程离开该组也会导致不平衡调用离开。
关于ios - 在重复的 for 循环中对 dispatch_group_leave() 的不平衡调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44772052/