내 스톱워치로 NSTIMER 문제
-
14-11-2019 - |
문제
여기에 내 문제가 있습니다. 시작 버튼을 클릭하면 타이머가 실행됩니다. STOP 버튼을 클릭하면 멈 춥니 다.그러나 시작 버튼을 클릭하면 0으로 돌아갑니다.타이머가 멈춘 곳에서 시작 버튼을 계속하고 싶습니다.
.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″;
}
.
감사합니다
해결책
You have a problem dealing with state. One state would be that the start button is pushed, but the reset button has not been pushed before it. Another state is that the start button is pushed, and the reset button has been pushed before it. One thing you can do is create an iVar to keep track of this state. So use a BOOL like this:
First declare the iVar:
BOOL resetHasBeenPushed;
Initialize the value to NO.
Then do this
- (IBAction)onResetPressed {
stopWatchLabel.text = @”00:00:00:000″;
resetHasBeenPushed = YES;
Now you need to set it back to NO, at some point, and that might be done in the start method:
- (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;
}
}
By the way, if you make your NSDateFormatter in iVar, you don't need to initialize it repeatedly. Movethe following lines to you inti code, or osmewhere it only runs once:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
UPDATE
Try this:
- (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];
}