0
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myMethod) userInfo:nil repeats:YES];

-(void)myMethod {
//my every second requirment

//my every minute requirment
}

My timer tics every second and its my requirement but I have another requirement that for example when my app starts its 10:05:30 am I want to trigger some code when its 10:06:00 and again when its 10:07:00 and this goes on.

I was thinking to do like this

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

But its not looking like a good solution to me, Is there any better solution?

2 Answers2

1

This solution is much more efficient, but please take into account 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;
    }
}
Ruslan Serebriakov
  • 640
  • 1
  • 4
  • 12
0

This solution simply adjust the timer fire date instead of keep your timer working every one second, adjusting the timer fire time, allow us keep your timer with an interval of 60 secs as should be

- (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");
}

This works like a clock, ;)

Reinier Melian
  • 20,519
  • 3
  • 38
  • 55