NSTimer does not start on the specified date

I create 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 does not start. The method will not be called. 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

Isn't that "2012-10-12 15:21:02"? Somehow the clock is 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 on 2012-10-12 13:19:02 plus two seconds.

What am I doing wrong?

Thanks!

+4
source share
2 answers

Time created using initWithFireDate should be added to the run loop, for example

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

Use scheduledTimerWithTimeInterval to create a timer that is automatically assigned in the current run loop.

PS: the description method NSDate always uses GMT, which probably explains your conclusion.

+16
source

addTimer If you create your timer as follows:

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

You must add a timer to RunLoop as follows:

 [[NSRunLoop currentRunLoop] addTimer:saveProgressSizeTimer forMode:NSDefaultRunLoopMode]; 
+1
source

Source: https://habr.com/ru/post/1439390/


All Articles