Search code examples
iosobjective-cnstimer

Second NSTimer not working?


I previously had a single NSTimer which is working fine. I have added another NSTimer to my runloop as now I need to call two functions repeatedly after a delay. Both functions have a different delay. My code is given below.

self.now = [NSDate date] ;
    self.timer = [[NSTimer alloc] initWithFireDate:self.now
                                          interval:500
                                            target:self
                                          selector:@selector(Func1)
                                          userInfo:nil
                                           repeats:YES] ;

    self.runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:self.timer forMode:NSDefaultRunLoopMode];
    [self.runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:10000]];


    //Second timer start here.its not working.The function 'func2' is not getting called

    self.now = [NSDate date] ;
    self.timer = [[NSTimer alloc] initWithFireDate:self.now
                                          interval:60
                                            target:self
                                          selector:@selector(Func2)
                                          userInfo:nil
                                           repeats:YES] ;

    self.runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:self.timer forMode:NSDefaultRunLoopMode];
    [self.runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:10000]];

The first NSTimer is still working but the second NSTimer doesn't work.


Solution

  • You have to declare a second property of NSTimer. Currently you are overwriting your first timer when doing this

    self.timer = [[NSTimer alloc] initWithFireDate:self.now
                                          interval:60
                                            target:self
                                          selector:@selector(Func2)
                                          userInfo:nil
                                           repeats:YES] ;
    

    Declare timer2 in your interface analogues to your timer declaration and the use self.timer2 to store the second timer.