Performselector afterdelay not working

I use the following method in a uiview subclass:

[self performSelector:@selector(timeout) withObject:nil afterDelay:20]; 

The method is called after 20 seconds, as expected. In another method, I am trying to cancel a request for execution using the following code:

 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeout) object:nil]; 

I also tried

 [NSRunLoop cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeout) object:nil]; 

both messages do not produce the expected result until the timeout method is called. can someone explain to me what i am doing wrong and how to do it right?

cheers from austria martin

+6
source share
4 answers

Two points
1. Are both self the same object?
2. Whether [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeout) object:nil]; in the same thread that you called [self performSelector:@selector(timeout) withObject:nil afterDelay:20]; ?

Check out these two issues.

+3
source

Use NSTimer, which is stored as an instance variable in your class. If you want to cancel execution, cancel and destroy the timer.

In your @interface:

 @property (readwrite, retain) NSTimer *myTimer; 

In your @implementation:

 self.myTimer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(timeout) userInfo:nil repeats:NO]; 

Then, if some condition is met, and the timeout method should no longer be called:

 [self.myTimer invalidate]; self.myTimer = nil; // this releases the retained property implicitly 
+3
source

You can do this in two ways:

  • You can use this to delete all queues.

    [NSObject cancelPreviousPerformRequestsWithTarget: self];

  • you can delete each one individually

    [NSObject cancelPreviousPerformRequestsWithTarget: self selector: @selector (timeout) Object: zero];

+1
source

Try the following:

 [self performSelectorOnMainThread:@selector(timeout) withObject:self waitUntilDone:NO]; 
+1
source

Source: https://habr.com/ru/post/909045/


All Articles