How to check if there's a performSelector: waiting to be executed?

萝らか妹 提交于 2019-12-09 17:12:26

问题


In my iPhone app I got several places where I can do a

[object performSelector: withObject: afterDelay:]

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

But, is there a way to tell if there are any other method calls waiting to be executed?

I could use a counter in this class that I would increment each time I set this perform after delay, then decrement it at start of each call and only execute the code if this counter is zeroed. But I'm wondering if it's the best/acceptable approach...


回答1:


Well what you could do is this: anytime you call [object performSelector: withObject: afterDelay:] just add the line you mentioned above it. You could actually create a method that handles that 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 where ever you use [object performSelector: withObject: afterDelay:] just replace it with [self performSelectorOnce: withObject: afterDelay:];

If you want to use this in multiple objects than you could actually create an NSObject category and add the method there.

Let me know if this works for you.



来源:https://stackoverflow.com/questions/7659584/how-to-check-if-theres-a-performselector-waiting-to-be-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!