How to check if there is a run function: pending execution?

In my iPhone application, I have several places where I can do

[object performSelector: withObject: afterDelay:]

call. All lead to the same method. Now, in this method, I want to execute some code only when it was last called. If this were the first, I could just do [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(thisMethod) object:nil] and be sure that it will be called once.

But is there a way to find out if there are any calls to other methods that are awaiting execution?

I could use a counter in this class, which I would increment every time I set this execution after a delay, and then decrease it at the beginning of each call and only execute code if that counter is reset. But I wonder if this is the best / acceptable approach ...

+7
source share
1 answer

Well, what you could do is: anytime you call [object performSelector: withObject: afterDelay:] , just add the line above. You could create a method that handles this for you. For example:

 - (void)performSelectorOnce:(SEL)selector withObject:(id)object afterDelay:(NSTimeInterval)delay { [NSObject cancelPreviousPerformRequestsWithTarget:object selector:selector object:object]; [self performSelector:selector withObject:object afterDelay:delay]; } 

and than you ever use [object performSelector: withObject: afterDelay:] , just replace it with [self performSelectorOnce: withObject: afterDelay:];

If you want to use this in several objects, than you could create an NSObject category and add a method there.

Let me know if this works for you.

+6
source

All Articles