5

This is my exact code, and it doesn't seem to be working. Can you tell me what I am doing wrong? Note that refreshTimer was already 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");
}
Redneys
  • 285
  • 1
  • 6
  • 18

2 Answers2

16

Give scheduledTimerWithTimeInterval a try:

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

Quoting: NSTimer timerWithTimeInterval: not working

scheduledTimerWithTimeInterval:invocation:repeats: and scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: create timers that get automatically added to an NSRunLoop, meaning that you don't have to add them yourself. Having them added to an NSRunLoop is what causes them to fire.

Community
  • 1
  • 1
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
7

There is two-option.

If using a timerWithTimeInterval

use a following like it.

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

also mode is two-option. NSDefaultRunLoopMode vs NSRunLoopCommonModes

more Information. refer a this documentation: RunLoopManagement


If using a scheduledTimerWithTimeInterval

use a following like it.

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 a this documentation: Timer Programming Topics

In summary

The "timerWithTimeInterval" you have to remember to add the timer to the run loop that you want to add on.

The "scheduledTimerWithTimeInterval" default auto creates a timer that runs in the current loop.

bitmapdata.com
  • 9,572
  • 5
  • 35
  • 43