How to disable the timer when I do not create an NSTimer object

I do not want to create an NSTimer object. How can I invalidate a timer? I want to invalidate the timer in viewWillDisappear.

-(void) viewDidLoad { [super viewDidLoad]; [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES]; } 
+6
source share
4 answers

A

you need to hold the timer you create:

 @interface MONObject () @property (nonatomic, retain) NSTimer * timerIvar; @end @implementation MONObject ... - (void)viewDidLoad { [super viewDidLoad]; self.timerIvar = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES]; } - (void)invalidateTimer { [self.timerIvar invalidate]; self.timerIvar = nil; } - (void)viewWillDisappear:(BOOL)animated { ... [self invalidateTimer]; } 

IN

another option is to invalidate the timer that is passed in the callback, but that will not happen within viewDidUnload: therefore, in this case this is not entirely applicable:

 - (void)onTimer:(NSTimer *)pTimer { [pTimer invalidate]; } 
+3
source

If you want to cancel the timer, you need to turn to cancel the timer, and this means that you must keep the pointer on the timer around, see the response to the request.

Saving a timer reference is the right way to do this, but for completeness, you can also use the -performSelector:withObject:afterDelay: as a poor timer. This call can be canceled using +cancelPreviousPerformRequestsWithTarget: Code example:

 - (void) viewDidLoad { [super viewDidLoad]; [self performSelector:@selector(timerTick) withObject:nil afterDelay:10]; } 

And then:

 - (void) viewWillDisappear { [NSObject cancelPreviousPerformRequestsWithTarget:self]; [super viewWillDisappear]; } 

But this is not the right way to do this, because there may be other selection requests awaiting your object that you cancel. It’s best to keep the timer around so you know exactly what you are canceling.

By the way, its also probably a good idea to start a timer in -viewDidLoad . Download viewing can happen at any time without any relation to viewing.

+1
source

Perhaps this method may help you:

 [self performSelector:@selector(onTimer:) withObject:nil afterDelay:10]; 
0
source

If you don’t want to hold your timer, the NSTimer object will be passed to the timer method (in your case, onTimer :), so in this method you can check if the timer is needed and it is invalid, However, you will encounter a problem if the view returns, before you canceled the timer and you will create a new one.

The best way is to save the timer in an instance variable. It works, no smart tricks, and you will know in six months what you have done. I would probably write

 @property (readwrite, nonatomic) BOOL hasTimer; 

getter returns YES if the timer is not zero, setter invalidates the timer or creates a new one.

0
source

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


All Articles