gpt4 book ai didi

ios - 多个完成 block 完成后执行的函数

转载 作者:搜寻专家 更新时间:2023-11-01 06:05:08 25 4
gpt4 key购买 nike

我有一个函数,我只想在两个完成 block 完成时才执行(而且无法判断先完成哪个)。以下是我的尝试。然而,它非常困惑,如果我要等待三个或更多的完成 block ,我会到处都有标志。我想知道是否有更漂亮的方法。

class TestClass: UIViewController {
var blockOneComplete = false
var blockTwoComplete = false

func blockOneDownloadImageDescription(completion:()->Void) {
downloadAsyncWithCompletion {
blockOneComplete = true
if self.blockTwoComplete == true {
self.allDataDownloadCompleted()
} else {
// Do nothing and wait for block Two to complete
}
}
}

func blockTwoDownloadImageData(completion:()->Void) {
downloadAsyncWithCompletion {
blockTwoComplete = true
if self.blockOneComplete == true {
self.allDataDownloadCompleted()
} else {
// Do nothing and wait for block One to complete
}
}
}

func allDataDownloadComplete() {
// Execute this funciton after all Async Download has complete
}
}

-- 更新最终结果 --事实证明,该网站中概述的内容正是我所需要的 Using dispatch groups to wait for multiple web services

我相信这不是评论中提到的 SO 问题的重复,因为最终解决方案包括 dispatch_group_enter 和 dispatch_group_leave

最佳答案

最好的选择是使用 dispatch_group

class TestClass: UIViewController {

var group : dispatch_group_t = dispatch_group_create()

override func viewDidLoad() {
super.viewDidLoad()
dispatch_group_notify(group, dispatch_get_main_queue()) {
allDataDownloadComplete()
}
}

func blockOneDownloadImageDescription(completion:()->Void) {
dispatch_group_enter(group)
downloadAsyncWithCompletion {
dispatch_group_leave(group)
}
}

func blockTwoDownloadImageData(completion:()->Void) {
dispatch_group_enter(group)
downloadAsyncWithCompletion {
dispatch_group_leave(group)
}
}

func allDataDownloadComplete() {
// Execute this funciton after all Async Download has complete
}
}

关于ios - 多个完成 block 完成后执行的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39588755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com