Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer doesn't get fired at specified date

I'm creating an NSTimer:

    NSTimer *saveProgressSizeTimer = [[NSTimer alloc]
    initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:2.0f]
    interval:1.0f
    target:self
    selector:@selector(myMethod:)
    userInfo:myUserInfo
    repeats:YES];

However, the timer doesn't get fired. The method doesn't get invoked. If I print my date I get the following:

2012-10-12 15:19:02.786 MyApp[1768:303] fire date: 2012-10-12 13:21:02 +0000

Shouldn't it be "2012-10-12 15:21:02" ? Somehow the hours are wrong. But why? If I change the Time Zone from UTC/GMT +1 hour (I'm sitting in Germany) to another, the date is still 2012-10-12 13:19:02 plus two seconds.

What am I doing wrong?

Thanks!

like image 774
Daniel Avatar asked Dec 04 '22 01:12

Daniel


2 Answers

A time created with initWithFireDate must be added to a run loop, e.g.

[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

Use scheduledTimerWithTimeInterval to create a timer that is automatically scheduled on the current run loop.

PS: The description method of NSDate uses always GMT, that probably explains your output.

like image 147
Martin R Avatar answered Dec 11 '22 17:12

Martin R


addTimerIf you create your timer like this:

NSTimer *saveProgressSizeTimer = [[NSTimer alloc]
    initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:2.0f]
    interval:1.0f
    target:self
    selector:@selector(myMethod:)
    userInfo:myUserInfo
    repeats:YES];

You must add the timer in the RunLoop like this:

[[NSRunLoop currentRunLoop] addTimer:saveProgressSizeTimer forMode:NSDefaultRunLoopMode];
like image 35
Daniel Avatar answered Dec 11 '22 19:12

Daniel