我是苹果公司的GCD新手,并且与DispatchGroup
存在问题。 因此,我试图在帖子完全初始化后将帖子附加到地图上。在post.init
内部,有一个URLSession
从url下载UIImage
。但即使在下载完成之前,group.notify
也会被解雇。我无法真正找到原因。以下是代码。我真的很感激任何建议或帮助!谢谢。调度组在工作完成前通知
// ViewController.swift
let group = DispatchGroup
...
...
group.enter()
DispatchQueue.global(qos: .userInitiated).async {
post = Post(values: post)
self.posts[postId] = post
group.leave()
}
group.notify(queue: DispatchQueue.main, execute: {
print("notify:: \(post?.picture)") // This prints out nil, when it shouldn't.
self.addPostToMap(post!, at: location!)
})
// Post.swift
class Post {
var picture: UIImage?
var thumbnail: UIImage?
init(values: [String: Any]) {
...
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
DispatchQueue.main.async {
self.picture = UIImage(data: data!)
self.thumbnail = Util.resizeImage(image: self.picture!, targetSize: CGSize(width: 50, height: 50))
}
}).resume()
}
}
感谢您的回复,但取出通知将是一个问题,因为我现在无法从'didFinish'访问变量'post'和'location'。对此有何建议? –
其实我做到了!我通过委托方法传递了变量。谢谢! –