所以,我正在做一个异步查询,返回多个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中使用__block变量一样,但这不起作用,块交互只是忽略了值,你可以看到在输出中:
weakWorkerIndex = 0 worker 0 weakWorkerIndex = 1 worker 1 block weakWorkerIndex = 0 workerIndex 2 block weakWorkerIndex = 0 workerIndex 2 block weakWorkerIndex = 0 workerIndex 2
顺便说一句:我删除了任何不必要的代码以简化阅读。