Hon*_*ang 1 nsdate nstimer nstimeinterval ios ios7
我的意思是12:01:00,12:02:00
在iOS7中,我想在一小段时间改变时调用一个方法.换句话说,如果现在是01:55:47,那么我想在01:56:00 - > 01:57:00 - > 01:58:00调用方法...
我发现调用方法只是关于TimeInterval,但不是我想要的.
我试过这段代码:
NSTimeInterval roundedInterval = round([[NSDate date] timeIntervalSinceReferenceDate] / 60.0) * 60.0;
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:roundedInterval];
NSTimer *timer = [[NSTimer alloc] initWithFireDate:date
interval:60.0
target:self
selector:@selector(handleEveryMinutes:)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
- (void)handleEveryMinutes:(NSTimer *)timer {
NSLog(@"one minute!");
}
Run Code Online (Sandbox Code Playgroud)
但是这个方法不会在第二个0调用.
希望很酷的人可以帮助我!
- - - 我的答案 - - - -
我也弄清楚为什么我的代码工作不正常,我需要额外增加60秒到roundedInterval,这是下一分钟的确切时间.如果不添加60秒,则会传递fireDate,因此当我运行我的应用程序时,它必须立即触发.
NSTimeInterval roundedInterval = round([[NSDate date] timeIntervalSinceReferenceDate] / 60.0) * 60.0 + 60; // the extra 60 is used to set the correct time Interval between next minute and referenced date.
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:roundedInterval];
Run Code Online (Sandbox Code Playgroud)
现在,它正在运作!
关键是在合适的时间启动定期计时器.获取当前时间并了解我们当前分钟的秒数...
NSDateComponents *components = [[NSCalendar currentCalendar] components: NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger second = [components second];
Run Code Online (Sandbox Code Playgroud)
从这里我们可以得到直到下一分钟的秒数......
NSInteger tillNextMinute = (60 - second) % 60;
Run Code Online (Sandbox Code Playgroud)
我没有测试过,但mod 60的想法是处理第二个为零时的情况.现在我们差不多完成了......
[self performSelector:@selector(startTimer) withObject:nil afterDelay:tillNextMinute];
Run Code Online (Sandbox Code Playgroud)
那你开始的代码......
- (void)startTimer {
// contains the code you posted to start the timer
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2120 次 |
| 最近记录: |