Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to prevent method from being called by different entities simultaneously

I have a method, someMethod, that is called when a) the user taps the view and b) when a user drags the view. In someMethod, there is a UIView animateWithDuration block that makes the toolbar on top of the view disappear, and resets its frame accordingly. If the user taps the view, than drags it, someMethod will be fired while the animation is still completing, and this isn't the behavior I want (simply canceling the animation doesn't work because the completion block still fires (even if I check the 'finished' BOOL). All things being considered, I just don't want this method to be fired while the animation is still in progress.

Obviously an easy solution to this is to set a manual lock with a BOOL and only allow the method to be called once the lock is free.

I'm wondering, is there a more elegant way to accomplish this? Possible to use GCD or some other library to accomplish this so it's more fool proof?

Update: I did try to use synchronized, the problem though is the method fires off the animation, finishes, but the animation is still running on another thread. Any other ideas?

like image 641
Ser Pounce Avatar asked Jan 22 '26 13:01

Ser Pounce


1 Answers

A timer running out does not imply or require a secondary thread. You're in control of what thread a timer is scheduled on. If you just schedule the timer on the main thread, then both things happen on the main thread.

The suggestions of using @synchronized achieve the effect that a given block of code is not running for the same object (whatever is the parameter of @synchronized) at the same time, but that's not the same thing as saying it's not run on two different threads.

If you want to detect if a method is called on a thread other than the main thread and then shunt it over to the main thread, you can use +[NSThread isMainThread] and dispatch_async(dispatch_get_main_queue(), ^{ /* re-call current method */ });.

like image 130
Ken Thomases Avatar answered Jan 25 '26 09:01

Ken Thomases



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!