Reputation: 978
I have a function that I want only to execute if not executing currently. I have used a bool variable to check the current execution.
Is there any other solution provided by Swift to handle this instead of using Bool?
guard
!isExecuting,
let currentNavVC = tabBarController.selectedViewController as? UINavigationController
else { return }
isExecuting = true
let first = currentNavVC.viewControllers.first,
let last = currentNavVC.viewControllers.last
var controllers = [first]
if first != last {
controllers = [first, last]
}
DispatchQueue.main.async {
currentNavVC.viewControllers = controllers
isExecuting = false
}
Bool variable: isExecuting
Tried using Semaphores(DispatchSemaphore) but they are of no help.
Also I am calling the above function in didReceiveMemoryWarning()
Any help will be appreciated and thanks in advance!!
Upvotes: 0
Views: 166
Reputation: 846
I believe you also can use Operation
with OperationQueue
in this case.
Operation
supports cancellation as well as checking if it is executing.
Ref:
OperationQueue: https://developer.apple.com/documentation/foundation/operationqueue
Operation: https://developer.apple.com/documentation/foundation/operation
Upvotes: 1
Reputation: 535138
I have a function that I want only to execute if not executing currently
You're looking for a lock. But locks of themselves are tricky and dangerous. The easy, safe way to get a lock is to use a serial queue. As we say, a serial queue is a form of lock. So:
If your function is called on the main queue, then it cannot execute if it is executing currently, and there is nothing to do. The main queue is a serial queue and there can be Only One.
If your function is called on a background queue, then make sure that your queue is a serial queue. For example, if you create your own DispatchQueue, it is serial by default.
Upvotes: 4