2017-11-26 2 views
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 
} 

내 타이머 틱 초마다하고 내 요구 사항을하지만 난 때 몇 가지 코드를 트리거 할 예를 들어 내 응용 프로그램은 오전 10시 5분 30초을 시작하는 또 다른 요구 사항이있는 그 10:06:00 그리고 다시 10:07:00이되면 계속됩니다.추출 분 양식 NSTimer 어느 틱 초마다

I는 나에게 좋은 해결책처럼 보이는없는이

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 분마다? 그게 네가 필요한거야? –

+0

내 대답을 확인할 수 있습니까? –

답변

1

이 솔루션은 훨씬 더 효율적이지만, 우리를 허용, 타이머 화재 시간을 조정,이 솔루션은 단순히 타이머 화재 날짜를 조정하는 대신 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; 
    } 
} 
+0

위대한 솔루션에 감사드립니다. –

+0

@Pursuingperfection 나는 내 대답을 선택 취소했다. 어떤 문제가 있습니까? –

+0

여러 계산이 1 초 안에 진행되므로 잠시 후에 더 많은 시간이 걸릴 수 있습니다. 솔루션의 숫자가 증가하므로 몇 라운드가 증가하고 시간이 동기화되지 않습니다. –

0

에 확인하시기 바랍니다 이 시계처럼 작동

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

이어야으로 60 초 간격으로 타이머를 유지)