我遇到了一些CoreData并发问题。
当目标线程被context.perform
阻止时,我无法DispatchGroup
。
以下是一个显示问题的简单示例:
func upload(objects: [NSManagedObject]) {
let group = DispatchGroup()
for object in objects {
group.enter()
upload(object) {
group.leave()
}
}
group.wait() // current thread is blocked here
someAdditionalWorkToDoInSameThread()
}
func upload(object: NSManagedObject, completion: ()->()) {
let context = object.managedObjectContext
performAlamofireRequest(object) {
context.perform {
// can't reach here because the thread is blocked
update(object)
completion()
}
}
}
请帮助我重新实现这一点。感谢。
答案 0 :(得分:2)
在调度组上使用notify而不是等待,应解决您的问题。
调用wait()
阻止当前线程完成以前提交的工作。
notify(queue:execute:)
将通知您传递的队列作为组任务已完成的参数。
func upload(objects: [NSManagedObject], completion: ()->()) {
let group = DispatchGroup()
for object in objects {
group.enter()
upload(object) {
group.leave()
}
}
group.notify(queue: DispatchQueue.main) {
completion()
}
}