问题
I am making a stopwatch in Objective-C:
- (void)stopwatch
{
NSInteger hourInt = [hourLabel.text intValue];
NSInteger minuteInt = [minuteLabel.text intValue];
NSInteger secondInt = [secondLabel.text intValue];
if (secondInt == 59) {
secondInt = 0;
if (minuteInt == 59) {
minuteInt = 0;
if (hourInt == 23) {
hourInt = 0;
} else {
hourInt += 1;
}
} else {
minuteInt += 1;
}
} else {
secondInt += 1;
}
NSString *hourString = [NSString stringWithFormat:@"%d", hourInt];
NSString *minuteString = [NSString stringWithFormat:@"%d", minuteInt];
NSString *secondString = [NSString stringWithFormat:@"%d", secondInt];
hourLabel.text = hourString;
minuteLabel.text = minuteString;
secondLabel.text = secondString;
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:YES];
}
The stopwatch has three separate labels, if you were wondering, for hours, minutes and seconds. However, instead on counting by 1, it counts like 2, 4, 8, 16, etc.
Also, another issue with the code (quite a minor one) is that it doesn't display all numbers as two digits. For example it's shows the time as 0:0:1, not 00:00:01.
Any help is really appreciated! I should add that I am really new to Objective-C so keep it as simple as possible, thank you!!
回答1:
Don't use repeats:YES
if you schedule the timer at every iteration.
You're spawning one timer at every iteration and the timer is already repeating, resulting in an exponential growth of timers (and consequently of method calls to stopwatch
).
Change the timer instantiation to:
[NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(stopwatch)
userInfo:nil
repeats:NO];
or start it outside the stopwatch
method
For the second issue simply use a proper format string.
NSString *hourString = [NSString stringWithFormat:@"%02d", hourInt];
NSString *minuteString = [NSString stringWithFormat:@"%02d", minuteInt];
NSString *secondString = [NSString stringWithFormat:@"%02d", secondInt];
%02d
will print a decimal number padding it with 0
s up to length 2, which is precisely what you want.
(source)
回答2:
For the first issue, instead of creating a timer instance for every call.Remove the line
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:YES];
from the function stopwatch.
Replace your call to function stopwatch with the line above. i.e replace
[self stopwatch]
with
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:YES];
来源:https://stackoverflow.com/questions/18419736/stopwatch-counting-in-powers-of-2