问题
I am trying to use dispatch groups to wait for two asynchronous processes to finish. However the second asynchronous function loops to the amount of messages I have in my database.
The code below crashes because the number of dispatch is not balanced since dispatch leave is higher than the number of dispatch enters due to the multiple executions of the second asynchronous function. Is there a different way to implement dispatch groups in this case.
dispatch_group_enter(dispatch_group)
ref.observeEventType(.ChildAdded, withBlock: {(snapshot) in
//execute once
dispatch_group_leave(self.dispatch_group)
}
dispatch_group_enter(dispatch_group)
ref.observeEventType(.ChildAdded, withBlock: {(snapshot) in
//execute 1000 times
dispatch_group_leave(self.dispatch_group)
}
dispatch_group_notify(self.dispatch_group, dispatch_get_main_queue()) {
print("done")
}
回答1:
Its been a while since this was asked, but here is a possible solution. It is crashing because you are entering the group once, but leaving it about 1000 times in:
dispatch_group_enter(dispatch_group)
ref.observeEventType(.ChildAdded, withBlock: {(snapshot) in
//execute 1000 times
dispatch_group_leave(self.dispatch_group)
}
You have to make sure, that you only leave the group as often as you´ve entered it.
来源:https://stackoverflow.com/questions/39188005/dispatch-group-crashing-because-asynchronous-function-executes-multiple-time