私は後処理をやろうとしていますSwiftでカスタム補完ブロックを作成する方法
a。私の非同期機能の1つが終了したら
b。一度すべての私の非同期機能が終了した。
残念ながら、私は以下のコードで競合状態に陥ります。
func foo(stuff: AnArrayOfObjects, completed: (NSError?)->()) {
// STEP 1 OF CREATING AN OVERALL COMPLETION BLOCK: Create a dispatch group.
let loadServiceGroup: dispatch_group_t = dispatch_group_create()
// Define errors to be processed when everything is complete.
// One error per service; in this example we'll have two
let configError: NSError? = nil
let preferenceError: NSError? = nil
// some more preprocessing/variable declarations here. E.g.:
var counter = 0
// STEP 2 OF CREATING AN OVERALL COMPLETION BLOCK: Adding tasks to a dispatch group
dispatch_group_enter(loadServiceGroup)
// here i may start MULTPILE functions that are asynchronous. For example:
for i in stuff {
estore.fetchRemindersMatchingPredicate(remindersPredicate) {
// MARK: Begininning of thread
// does something here. E.g., count the elements:
counter += 1
// update the UI
dispatch_async(dispatch_get_main_queue()) {
self.sendChangedNotification() // reloads the tableview.
// WARNING: I CAN'T JUST SHOW THE counter RESULTS HERE BECAUSE IT MIGHT NOT BE DONE YET. IT IS ASYNCHRONOUS, IT MIGHT STILL BE RUNNING.
}
}
// STEP 3 OF CREATING AN OVERALL COMPLETION BLOCK: Leave dispatch group. This must be done at the end of the completion block.
dispatch_group_leave(loadServiceGroup)
// MARK: End of thread
}
// STEP 4 OF CREATING AN OVERALL COMPLETION BLOCK: Acting when the group is finished
dispatch_group_notify(loadServiceGroup, dispatch_get_main_queue(), {
// do something when asychrounous call block (above) has finished running. E.g.:
print("number of elements: \(counter)")
// Assess any errors
var overallError: NSError? = nil;
if configError != nil || preferenceError != nil {
// Either make a new error or assign one of them to the overall error.
overallError = configError ?? preferenceError
}
// Call the completed function passed to foo. This will contain additional stuff that I want executed in the end.
completed(overallError)
})
}
あなたは_expecting_何であるか、そして、あなたが実際に経験しているものを追加する必要の実験です。潜在的なデータ競合があります:IFFステートメント 'counter + = 1'は異なるキューで実行されます(より正確には、同じ親キューを持たない)、このケースではデータ競合である異なるスレッドでアクセスされる可能性があります。 – CouchDeveloper