timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myMethod) userInfo:nil repeats:YES];
-(void)myMethod {
//my every second requirment
//my every minute requirment
}
我的计时器每秒都会抽搐并且是我的要求,但我有另一个要求,例如当我的应用程序启动时间为10:05:30时,我想触发一些代码,当它的10:06:00时再次触及它的10: 07:00然后继续。
我想这样做
date1 = dateFormatter ... date // this will give 10:05:30
date2 = dateFormatter ... date // this will give 10:05:00
date2 = addition of minute // this will give 10:06:00
and finally date1 compare date2 == descending // means it currently 10:06:00
但它看起来不是一个好的解决方案,有没有更好的解决方案?
答案 0 :(得分:1)
此解决方案效率更高,但请考虑a tolerance of the NSTimer
@interface ViewController ()
@property (nonatomic, assign) NSInteger timerMinuteAddition;
@end
@implementation ViewController
- (void)yourScope {
// Here you compute the initial addition to the full minute
NSDate *currentDate = [NSDate new];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitSecond fromDate:currentDate];
self.timerMinuteAddition = 60 - [components second];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myMethod) userInfo:nil repeats:YES];
}
- (void)myMethod {
// your every second requirment
self.timerMinuteAddition--;
if (self.timerMinuteAddition == 0) {
// your every minute requirment
self.timerMinuteAddition = 60;
}
}
答案 1 :(得分:0)
这个解决方案只是调整计时器开火日期,而不是让你的计时器每隔一秒工作一次,调整计时器开火时间,让我们保持你的计时器间隔60秒应该是
- (IBAction)startTimerCounting:(id)sender {
NSDate * date = [NSDate date];
NSInteger seconds = [[NSCalendar currentCalendar] component:NSCalendarUnitSecond fromDate:date];
NSLog(@"%i",seconds);
self.timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(myMethod) userInfo:nil repeats:YES];
if(seconds > 0){
NSDateComponents * components = [[NSDateComponents alloc] init];
[components setSecond:60 - seconds];
NSDate * fireDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:date options:NSCalendarMatchStrictly];
[self.timer setFireDate:fireDate];
}
}
- (void)myMethod{
NSLog(@"timer executed");
}
这就像一个时钟,;)