Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performselector afterdelay not working

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

like image 848
Martin Avatar asked Feb 22 '12 06:02

Martin


4 Answers

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.

like image 69
Inder Kumar Rathore Avatar answered Oct 31 '22 18:10

Inder Kumar Rathore


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
like image 32
bneely Avatar answered Oct 31 '22 18:10

bneely


Try this:

[self performSelectorOnMainThread:@selector(timeout) withObject:self waitUntilDone:NO];
like image 21
Roman J. Sabatini Avatar answered Oct 31 '22 17:10

Roman J. Sabatini


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];

like image 1
Alex Moskalev Avatar answered Oct 31 '22 17:10

Alex Moskalev