I made a simple popupView and add simple animation like these
// Present
if popup.superView != currentView { currentView.addSubview(popup) }
UIView.animate(withDuration: 0.3, animations: {
popup.alpha = 1
})
// Dismiss
UIView.animate(withDuration: 0.3, animations: {
popup.alpha = 0
}, completion: {
popup.removeFromSuperview()
})
But sometimes present and dismiss action triggered in mean time new present action is disabled by dismiss action's completion. so i add animationCount
var animationCount: Int = 0
// Present
if popup.superView != currentView { currentView.addSubview(popup) }
animationCount = 1
UIView.animate(withDuration: 0.3, animations: {
popup.alpha = 1
}, completion: {
animationCount -= 1
)
// Dismiss
animationCount = 1
UIView.animate(withDuration: 0.3, animations: {
popup.alpha = 0
}, completion: {
animationCount -= 1
if animationCount == 0 {
popup.removeFromSuperview()
}
})
it looks good and seems to run well. but i'm curious about data race of animationCount
in UIView.animate completion block. So my question is "Dose UIView.animate completion block run in main thread?" In my opinion, if it run on main thread there is no data race problem in animationCount
and there will be no situation popup dosen't remove in superView
If someone answer my question, it will be grateful Thank you!
CodePudding user response:
The answer is yes. But to be sure you can test it by adding a debug print:
UIView.animate(withDuration: 0.3, animations: {
popup.alpha = 0
}, completion: {
print("---- isMainThread: \(Thread.isMainThread) ----")
animationCount -= 1
if animationCount == 0 {
popup.removeFromSuperview()
}
})