cancelling queued performSelector:afterDelay calls

馋奶兔 提交于 2019-11-30 10:15:43

问题


does anybody know if it is possible to cancel already queued selector events from the event stack or timer stack (or whatever mechanism it is that is utilized by the API) when you call performSelector:withObject:afterDelay?

I was using this event stack to alter the attributes of an image within a TabBar tab, and would sometimes queue up to 10 seconds worth of changes in one quickly executed for loop... maybe 5 milliseconds or so.

the problem arises if the user switches tabs... like say I have the image alterations queued for an image that is displayed as soon as Tab #4 is enabled, and then the user quickly switches to Tab #3 and then right back to Tab #4... this would then re-queue another 10 seconds worth of alterations while the old queue was still playing, probably around 2 or 3 seconds in to the queue if switched quick enough... but even arriving at 5 seconds in to the stream was a problem.

so I needed some way to cancel the old stack of changes before putting a new stack on...

I'm writing this query in the past tense because I already came up with an alternative solution to this problem by adding a hawk-eyed event filter on the playback function. however I am still curious if event cancellation is possible, because I have a feeling such knowledge will come in handy in the future. thank you for any assistance rendered :)


回答1:


[NSObject cancelPreviousPerformRequestsWithTarget:]

or

[NSObject cancelPreviousPerformRequestsWithTarget:selector:object:]

The target is the original object on which performSelector:afterDelay: was called.

For example:

// schedule the selector
[self performSelector:@selector(mySel:) withObject:nil afterDelay:5.0];
// cancel the above call (and any others on self)
[NSObject cancelPreviousPerformRequestsWithTarget:self];

See apple docs, it's right at the end of the performSelector:withObject:afterDelay: description.




回答2:


In order to cancel all previous perform requests, you may use :

[NSObject cancelPreviousPerformRequestsWithTarget:self];   



回答3:


If you are looking for "performSelector" to have its matching "cancelPreviousPerformSelector"... it doesn't. (Ugh, Apple, why do you do that to me???)

The, er, ah, "matching" methods are:

performSelector

cancelPreviousPerformRequestsWithTarget

(Just to make it extra hard to remember, without searching the docs.)




回答4:


Check the NSRunLoop docs. You want -cancelPerformSelectorsWithTarget:



来源:https://stackoverflow.com/questions/1806445/cancelling-queued-performselectorafterdelay-calls

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