所以,我在做一个异步查询,它返回多个worker对象,每个worker都与workerperiod有一个关系,我用这个关系来做一个查询,问题是,这个查询是异步的,当它从web服务返回时,workerIndex就混乱了。
workerQuery.whereKey("construction", equalTo: currentConstruction).findObjectsInBackgroundWithBlock({ (unsafeWorkers, error) -> Void in
guard let workers = unsafeWorkers as? [Worker] where error == nil && workers.count == 0 else {
return
}
for var workerIndex = 0; workerIndex < workers.count; workerIndex++ {
let currentWorker = workers[workerIndex]
if let periodQuery = WorkerPeriod.query() {
periodQuery.whereKey("worker", equalTo: currentWorker)
let weakWorkerIndex = workerIndex
print("weakWorkerIndex = \(weakWorkerIndex) worker \(workerIndex)")
periodQuery.findObjectsInBackgroundWithBlock({ (unsafeWorkerPeriod, error) -> Void in
guard let workerPeriods = unsafeWorkerPeriod as? [WorkerPeriod] where error == nil && workerPeriods.count != 0 else {
return
}
print("block weakWorkerIndex = \(weakWorkerIndex) workerIndex \(workerIndex)")
.
.
})
}
}
我试图创建一个“weakworkerindex”作为一个let来保存值,就像我们在objective-c中对块变量所做的那样,但是这不起作用,块交互只是忽略了输出中的值:
weakWorkerIndex = 0 worker 0
weakWorkerIndex = 1 worker 1
block weakWorkerIndex = 0 workerIndex 2
block weakWorkerIndex = 0 workerIndex 2
block weakWorkerIndex = 0 workerIndex 2
顺便说一下:我删除了任何不必要的代码来简化阅读过程。
最佳答案
在完成处理程序中,您需要确保workerIndex
将按值捕获,例如:
for var workerIndex = 0; workerIndex < 10; workerIndex++ {
fooAsync { [workerIndex] in
print("\(workerIndex)")
}
}
见swiftCapture Lists
关于swift - 在Swift 2.1中阻止存储的var,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35159835/