gpt4 book ai didi

ios - 如何在 Swift4 中返回受线程影响的值

转载 作者:行者123 更新时间:2023-11-28 12:00:57 26 4
gpt4 key购买 nike

 func getAll(completion: (([Foods]?, Error?) -> Void)?){      
var foodWithEname: [Foods]?
let food: Food? = Food()
var sortedFood: [Foods]?
food?.getFoods(){ (foodsArray, error) in
sortedFood = foodsArray?.sorted{ (left, right) in
if let lh = left.hits {
if let rh = right.hits {
return left.hits! > right.hits!
}
return true
} else {
if let rh = right.hits {
return false
}
return false
}
}


for fa in foodsArray! {

var f = Foods(fid: fa.fid, fname: fa.fname, hits: fa.hits, addr: fa.addr, ename: nil)

food?.getEffectsById(fa.fid){ (effectsArray, error) in
//foodWithEname?.ename = effectsArray
print ("11111")

DispatchQueue.global().async {
f.ename = effectsArray
print ("2222")
foodWithEname?.append(f)
}
}

DispatchQueue.global().async (execute: {
print ("00000")

})

}
print("3333")
completion?(foodWithEname, nil)
}
print ("4444")
}

我需要向主视图返回 foodWithEname 值,但由于线程流,它没有返回值...

我不知道如何控制闭包流。

我在 MainView 中调用了函数:

let food: Food? = Food()
food?.getAll(){ (foodsArray, error) in

}

结果:444433330000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222111112222

我想要如下结果:

2222 00000 11111 2222 00000 11111 2222 00000 ... 3333

执行 completion?(foodWithEname, nil) 时,数组值应该在 foodWithEname 中。

请帮忙解决这个问题,谢谢!

最佳答案

在您的第二个循环中,您在一个循环中发送多个异步调用,在等待结果的同时您调用了完成处理程序,因此结果为空。

您需要在调度组中调用这些异步调用,并在所有执行完成后将结果返回给完成处理程序。

在第二个循环中做这样的事情:

// Create dispatch group
let group = DispatchGroup()

for fa in foodsArray! {

var f = Foods(fid: fa.fid, fname: fa.fname, hits: fa.hits, addr: fa.addr, ename: nil)

// Enter in group just before the call
group.enter()

food?.getEffectsById(fa.fid){ (effectsArray, error) in
//foodWithEname?.ename = effectsArray
print ("11111")

DispatchQueue.global().async {
f.ename = effectsArray
print ("2222")

// Leave the group when task is completed
group.leave()

foodWithEname?.append(f)
}
}

DispatchQueue.global().async (execute: {
print ("00000")

})
}
print("3333")

// Wait for all tasks to complete, and call the completion handler
group.notify(queue: DispatchQueue.main) {
completion?(foodWithEname, nil)
}

关于ios - 如何在 Swift4 中返回受线程影响的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50149608/

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