从后台线程返回函数

时间:2018-10-05 09:58:50

标签: ios swift multithreading

我的函数执行需要时间

    func hasValidValues() -> Bool{
        let leftValue = Double(leftTextValue) ?? 0
        let rightValue = Double(rightTextValue) ?? 0
        switch self.stackViewType {
            let leftValid = self.hasValidValue(min: targetMin, max: targetMax, value: CGFloat(leftValue), unitConversation: true)
            let rightValid = self.hasValidValue(min: 0, max: plusMinusLimit, value: CGFloat(rightValue), unitConversation: true)
            return leftValid && rightValid
}

现在我需要在后台线程中执行此操作,并想返回以便UI线程可以访问它,并且可以在另一个控制器中更改UI。

有人可以帮我吗?

3 个答案:

答案 0 :(得分:1)

使用DispatchQueue

DispatchQueue.global().async {
    let result = self.hasValidChanges()
    DispatchQueue.main.async {
        // Use result
    }
}

答案 1 :(得分:1)

因为每个线程都有自己的堆栈,所以您不能从另一个踏步返回值。因此,您必须在此处使用回调。

func checkValidValues(completionHandler: @escaping ((Bool) -> Void)) {
    DispatchQueue.global().async { [unowned self] in
        let result = self.hasValidChanges()
        DispatchQueue.main.async {
        completionHandler(result)
    }
}

答案 2 :(得分:0)

您可以使用dispatch group

var b: Bool = false
let queue = DispatchQueue(label: "myQueue")

let group = DispatchGroup()
group.enter()

DispatchQueue.global().async {
    b = hasValidValues()
    group.leave()
}

group.notify(queue: queue) {
    //use b
}
相关问题