DispatchGroup通知"Main"在斯威夫特 [英] DispatchGroup Not notifying 'Main" in Swift

查看:45
本文介绍了DispatchGroup通知"Main"在斯威夫特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Dispatch组在任务完成运行时通知我.我已经写了一份我想完成的简单的伪著作.由于某种原因,我的notify函数首先被调用.

I'm trying to use Dispatch group to notify me when a task is finished running. I've written a simple pseudo of what I'm trying to accomplish. For some reason my notify function gets called first.

    class Main {
        let cats = Cats()
        let all = ALL.singleton

        viewdidLoad(){
            cats.makeAllCall
            all.dis()
        }
    }


    class Cats {
    let dispatch = DispatchGroup()
    let all = ALL.singleton

    func makeAllCall(){
        for i in 1...10{
        all.callInfo()
        print("hello")
        }
    }
    }

    class ALL {
    static let singleton = ALL()
    let dispatch = DispatchGroup()

    func dis(){
        dispatch.notify(.main){
            print("working")
        }
    }

    func callInfo(){
        dispatch.enter()
    Alamofire.request("url", headers: headers).responseJSON { response in
            if response.result.isSuccess{
                completion(JSON(response.result.value!))
            }else{
                print("Binance - Couldn't import Request: Please check your internet connection")
            }
        }
        dispatch.leave()
        }
    }

推荐答案

您还不了解调度组的工作方式.您正在调用 dis(),显然是相信 dispatch.notify 是您所调用的东西.不是.当每个 enter leave 平衡后,就会为您调用.一个典型的结构如下所示的伪代码:

You have not understood how dispatch groups work. You are calling dis(), apparently in the belief that dispatch.notify is something that you call. It isn't. It is called for you when every enter has been balanced by a leave. A typical structure looks like this pseudo-code:

let group = DispatchGroup()
// here we go...
group.enter()
_queue1_.async {
    // ... do task here ...
    group.leave()
}
group.enter()
_queue2_.async {
    // ... do task here ...
    group.leave()
}
group.enter()
_queue3_.async {
    // ... do task here ...
    group.leave()
}
// ... more as needed ...
group.notify(queue: DispatchQueue.main) {
    // finished!
}

您需要摆脱这种奇怪的类结构,并放置所有内容-调度组, enter leave 调用以及 notify 阻止—一起放在一个地方.如果您不想这样做,那么这不是对调度组的好用(也许您想要的是像Operation和OperationQueue这样的东西).

You need to get rid of this bizarre class structure and put everything — the dispatch group, the enter and leave calls, and the notify block — together in one place. If you don't want to do that, then this is not a good use of a dispatch group (perhaps what you wanted was something like Operation and OperationQueue).

这篇关于DispatchGroup通知"Main"在斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆