ios - 如何让循环等待任务完成

标签 ios swift loops asynchronous dispatch

我知道这个主题已经有很多贡献。我尝试了不同的变体 DispatchGroup ,但似乎我无法让整个循环停止,直到某个任务完成。

let names = ["peter", "susan", "john", "peter", "susan", "john"]
var holding = [String: [Double]]()


for i in 0...10 {

    for name in names {

        if holding[name] == nil {
            Alamofire.request("https://jsonplaceholder.typicode.com", parameters: parameters).responseJSON { responseData in

                    // do stuff here
                    holding[name] = result
            }

        } else {
            // do other stuff with existing "holding[name]"

        }

        // if if holding[name] == nil, the whole process should wait
    }
}

如果我使用 DispatchGroup,Alamofire 请求会一个接一个地执行,但整个循环无法识别 holding[name] 是否已经存在。所以 holding[name] 总是 nil 因为循环不等待。

非常感谢!

编辑:

根据 Mikes 和 Versus 的回答,我尝试了以下方法:

var names = ["peter", "susan", "john", "peter", "susan", "john"]
var holding = [String: [Double]]()

let semaphore = DispatchSemaphore(value: 1)

for i in 0...10 {

    DispatchQueue.global().async { [unowned self] in
        self.semaphore.wait()

        for name in names {

            if holding[name] != nil {
                Alamofire.request("https://jsonplaceholder.typicode.com", parameters: parameters).responseJSON { responseData in

                    // do stuff here
                    holding[name] = result
                    semaphore.signal()
                }

            } else {
                // do other stuff with existing "holding[name]"
                semaphore.signal()

            }

            // if if holding[name] != nil, the wholeprocess should wait
        }
    }
}

但不幸的是,应用程序崩溃了。我做错了什么?

最佳答案

这里有两个选择

1 ) 信号量

2 ) 操作队列

但是在使用 Semaphores 之前你应该三思而后行

你需要小心 semaphore.signal()semaphore.wait()

因为 Semaphore 可能会阻塞 Main Thread 所以所有操作都应该在 Dispatch.global.async 中完成

semaphore.wait()

Alamofire.request("https://jsonplaceholder.typicode.com", parameters: parameters).responseJSON { responseData in

                     semaphore.signal()
                    holding[name] = result

 }

你在这里阻塞了主线程

问题在于完成处理程序在主线程中执行,该线程已被最初调用的 semaphore.wait() 锁定。所以当完成发生时, semaphore.signal() 永远不会被调用

你必须去

 DispatchQueue.global().async { [unowned self] in
        self.semaphore.wait()
        // And other statemetns 

    }

希望对你和其他人有帮助

关于ios - 如何让循环等待任务完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46091920/

相关文章:

ios - UIGestureRecognizer 与从另一个类调用选择器

objective-c - 指向 UITableViewCell 上自定义 UIView 的指针返回 0

ios - Xcode 6 在 OS X 10.10 上崩溃,异常名称为 : IBAssertionFailure

swift - WeiboSDK NSConcreteMutableData wbsdk_base64EncodedString错误

json - Swift 中的安全动态 JSON 转换

编码二叉搜索树

ios - osx 上的 sem_open 共享内存在哪里

ios - 在 UITableView 中正确显示 JSON 数据

mysql - 在存储过程中替换变量和游标的问题

python:将元素插入到元组列表内的元组中