gpt4 book ai didi

ios - 数组回调

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

我正在尝试设置以下方法,以便在执行完所有 show.getVideosForShow() 成功 block 并附加所有视频后执行成功 block 。注意:show.getVideosForShow() 是异步的,可能需要几秒钟才能得到结果。有人可以提供一些帮助吗?

private func getNextVideoRecommendations(success: ([Video]) -> ()) {
var relatedVideos = [Video]()
if let relatedShows = self.videoCurrentlyPlaying?.show?.getShowsWithSameGenre(fetchLimit: 3) {
for show in relatedShows {
show.getVideosForShow(tvSeason: nil, longForm: true, sortType: VideoSort.Latest, success: { (videos: [Video]) in
print("Found Related Show: \(show.title)")
if videos.count > 0 {
relatedVideos.append(videos[0])
}
})
}
print("Finished all operations")
success(relatedVideos)
}
}

最佳答案

这是 dispatch groups 的一个很好的用例,这允许您在所有操作完成后提交另一个 block :

private func getNextVideoRecommendations(success: ([Video]) -> ()) {
var relatedVideos = [Video]()
if let relatedShows = self.videoCurrentlyPlaying?.show?.getShowsWithSameGenre(fetchLimit: 3) {
<b>let group = dispatch_group_create()</b>
for show in relatedShows {
<b>dispatch_group_enter(group)</b> // start tracking one unit of work
show.getVideosForShow(tvSeason: nil, longForm: true, sortType: VideoSort.Latest, success: { (videos: [Video]) in
print("Found Related Show: \(show.title)")
if videos.count > 0 {
relatedVideos.append(videos[0])
}
<b>dispatch_group_leave(group)</b> // finish one unit of work
})
}
<b>dispatch_group_notify(group, dispatch_get_main_queue())</b> { // and when done...
print("Finished all operations")
success(relatedVideos)
}
}
}

关于ios - 数组回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37065020/

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