2012-02-29 2 views
0

여기 내 문제가 있습니다. 시작 버튼을 클릭하면 타이머가 실행되고 중지 버튼을 클릭하면 중지됩니다. 그러나 시작 버튼을 다시 클릭하면 0으로 돌아갑니다. 타이머가 멈춘 곳에서 시작 버튼을 계속하고 싶습니다.NSTimer 내 스톱워치 관련 문제

.h 

NSTimer *stopWatchTimer; 
    NSDate *startDate; 
    @property (nonatomic, retain) IBOutlet UILabel *stopWatchLabel; 
    - (IBAction)onStartPressed; 
    - (IBAction)onStopPressed; 
    - (IBAction)onResetPressed; 

.m 

    - (void)updateTimer 
    { 
    NSDate *currentDate = [NSDate date]; 
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate]; 
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval]; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"HH:mm:ss.SSS"]; 
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; 
    NSString *timeString=[dateFormatter stringFromDate:timerDate]; 
    stopWatchLabel.text = timeString; 
    } 
    - (IBAction)onStartPressed { 
    startDate = [NSDate date]; 
    // Create the stop watch timer that fires every 10 ms 
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 
    target:self 
    selector:@selector(updateTimer) 
    userInfo:nil 
    repeats:YES]; 
    } 
    - (IBAction)onStopPressed { 
    [stopWatchTimer invalidate]; 
    stopWatchTimer = nil; 
    [self updateTimer]; 
    } 
    - (IBAction)onResetPressed { 
    stopWatchLabel.text = @”00:00:00:000″; 
    } 

도와주세요 당신은 상태 다루는 문제가

답변

0

감사합니다. 하나의 상태는 시작 버튼이 눌러졌지만 재설정 버튼은 그 앞에 푸시되지 않았을 것입니다. 또 다른 상태는 시작 버튼이 눌려지고 재설정 버튼이 그 앞에 푸시 된 상태입니다. 당신이 할 수있는 한 가지는 iVar를 만들어이 상태를 추적하는 것입니다. 따라서이 같은 BOOL을 사용

BOOL resetHasBeenPushed; 

가 NO로 값을 초기화 :

첫 번째는 바르를 선언합니다.

은 그럼 당신은 어떤 시점에서, 다시 NO로 설정해야하는 지금이

- (IBAction)onResetPressed { 
    stopWatchLabel.text = @”00:00:00:000″; 
    resetHasBeenPushed = YES; 

수행하고이 시작 방법으로 수행 할 수 있습니다 경우, 그런데

- (IBAction)onStartPressed { 
    startDate = [NSDate date]; 
    // Create the stop watch timer that fires every 10 ms 
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 
    target:self 
    selector:@selector(updateTimer) 
    userInfo:nil 
    repeats:YES]; 
    resetHasBeenPushed = NO; 
} 
    } 

iVar에 NSDateFormatter를 만들면 반복해서 초기화 할 필요가 없습니다.

이 시도

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"HH:mm:ss.SSS"]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; 

UPDATE :

- (IBAction)onStartPressed { 
    if (resetHasBeenPushed== YES) { 
     startDate = [NSDate date]; // This will reset the "clock" to the time start is set 
    } 

    // Create the stop watch timer that fires every 10 ms 
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 
    target:self 
    selector:@selector(updateTimer) 
    userInfo:nil 
    repeats:YES]; 
    } 
당신 INTI 코드 Movethe 다음 줄, 또는 한 번만 실행 osmewhere