nstimer timerwithtimeinterval not working

nstimer timerwithtimeinterval not working  using -'ios,timer,nstimer'

I've created a test application with timer before implementing it in my project.
It was the first time I'm using timer.
But the issue is when I implemented timer using [NSTimer timerWithTimeInterval: target: selector: userInfo: repeats: ]; , it is not working.
Here is my code,

@interface uialertViewController : UIViewController

    NSTimer *timer;



@implementation uialertViewController
- (void)viewDidLoad {

    [self displayAlert];
    [super viewDidLoad];


    timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(hideandview) userInfo:nil repeats:NO];

    alert = [[UIAlertView alloc] initWithTitle:@"testing" message:@"hi hi hi" delegate:nil cancelButtonTitle:@"continue" otherButtonTitles:nil];
    [alert show];

    [alert release];
    alert = nil;




    [alert dismissWithClickedButtonIndex:0 animated:YES];

    [alert release];

    [self displayAlert];


Then I Changed [NSTimer timerWithTimeInterval: target: selector: userInfo: repeats: ]; with [NSTimer scheduledTimerWithTimeInterval: target: selector:userInfo: repeats: ]; , It is working. What was the issue with timerWithTimeInterval: ? Am I mising anything in my first implementation ? Thanks in advance.

asked Sep 21, 2015 by sachin valanju
0 votes

2 Answers

0 votes

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.

With timerWithTimeInterval:invocation:repeats: and timerWithTimeInterval:target:selector:userInfo:repeats:, you have to add the timer to a run loop manually, with code like this:

[[NSRunLoop mainRunLoop] addTimer:repeatingTimer forMode:NSDefaultRunLoopMode];

Other answers on here suggest that you need to call fire yourself. You don't - it will be called as soon as the timer has been put on a run loop.

answered Sep 21, 2015 by amit.gupta
0 votes

The difference between the two is that the timerWithTimeInterval method returns a NSTimer object that has not yet been fired. To fire the timer you have to use [timer fire]; On the other hand the scheduledTimerWithTimeInterval returns an NSTimer that has already been fired.

So, in your first implementation you were just missing [timer fire];

answered Sep 21, 2015 by vimaldas2005