NSTimer scheduleTimerWithTimeInterval: target: selector: userInfo: retries do not call the method

A timer never calls a method. What am I doing wrong? This is the code:

NSTimer *manualOverlayTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(hideManual) userInfo:nil repeats:NO]; 

method:

 -(void)hideManual 

thanks

+6
source share
5 answers

This is a thread issue. I have corrected:

 dispatch_async(dispatch_get_main_queue(), ^{ // Timer here }); 
+23
source

You do not need NSTimer for this type of job. To hide the view object after a certain period of time in the main thread, you can use the gcd dispatch_after method

  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 2.0), dispatch_get_main_queue(), ^(void){ // Your code }); 

where 2.0 is the number of seconds that elapses before a block is executed.

+2
source

Just use this

 [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(hideManual) userInfo:nil repeats:NO]; 

EDIT

This code works well when pressing btn (a UIButton ) and the called function -(void)btnPressed .

 -(void)btnPressed{ [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(hideManual) userInfo:nil repeats:NO]; } -(void)hideManual{ NSLog(@"Hi, I'm here!"); } 
+1
source

try the following:

 NSTimer *manualOverlayTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(hideManual) userInfo:nil repeats:YES]; repeat:YES instead of [[NSRunLoop currentRunLoop] addTimer:manualOverlayTimer forMode:NSDefaultRunLoopMode]; 
0
source

in code snippets, it does not show when and where NSTimer starts.

if you want to use NSTimer , you must start the timer after init, for example:

 NSTimer *_timer = [NSTimer scheduledTimerWithTimeInterval:2.f target:self selector:@selector(hideManual) userInfo:nil repeats:false]; [_timer fire]; 

but you can also use the following line in your any method:

 [self performSelector:@selector(hideManual) withObject:nil afterDelay:2.f]; 

in this case, it looks easier than working with NSTimer .

0
source

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


All Articles