performselector afterdelay not working

11,250

Solution 1

Two points
1. Are both self same object??
2. Is [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeout) object:nil]; performed on same thread on which you called [self performSelector:@selector(timeout) withObject:nil afterDelay:20]; ?

Check these two problems.

Solution 2

Use an NSTimer stored as an instance variable in your class. When you want to cancel the perform, invalidate 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 happens and the timeout method should no longer be called:

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

Solution 3

Try this:

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

Solution 4

You can do that with 2 ways :

  1. You could use this which would remove all queued

    [NSObject cancelPreviousPerformRequestsWithTarget:self];

  2. you can remove each one individually

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

Share:
11,250
Martin
Author by

Martin

Updated on July 19, 2022

Comments

  • Martin
    Martin almost 2 years

    i am using 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 try to cancel the perform request using the following code:

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

    i've also tried

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

    both messages don't bring the expected result an the timeout method is still called. can anybody explain me what i am doing wrong and how to do it the right way ?

    cheers from austria martin