IOS NSTimer not working?

This is my exact code, and it does not seem to work. Can you tell me what I'm doing wrong? Note that refreshTimer has already been declared in the private interface.

-(void)viewDidLoad { refreshTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerTest) userInfo:nil repeats:YES]; } -(void)timerTest { NSLog(@"Timer Worked"); } 
+4
source share
2 answers

Give scheduledTimerWithTimeInterval try:

 NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myMethod) userInfo:nil repeats:YES]; 

Quote: NSTimer timerWithTimeInterval: not working

scheduledTimerWithTimeInterval:invocation:repeats : and scheduledTimerWithTimeInterval:target:selector:userInfo:repeats : create timers that are automatically added to NSRunLoop , which means you don't need to add them yourself. Adding them to NSRunLoop will trigger them.

+16
source

There are two options.

If using timerWithTimeInterval

use the following like.

 refreshTimer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerHandler) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:refreshTimer forMode:NSRunLoopCommonModes]; 

also the mode has two options. NSDefaultRunLoopMode vs NSRunLoopCommonModes

Additional Information. refer to this documentation: RunLoopManagement


If scheduledTimerWithTimeInterval used

use the following like.

 refreshTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerHandler) userInfo:nil repeats:YES]; 

scheduled timers are automatically added to the run loop.

more information. refer to this documentation: Timer programming topics

Finally

" timerWithTimeInterval " you must remember to add a timer to the run loop you want to add.

Automatically, by default, " scheduledTimerWithTimeInterval " creates a timer that starts in the current loop.

+7
source

All Articles