I am making a stopwatch app. I am counting the time elapsed since the app was in the background, so that I can add it on to the stopwatch time when the app returns to the foreground. I have this code which is called when an NSNotification is sent to my StopwatchViewController with the elapsed time in seconds. I am trying to convert the seconds into hours, minutes and seconds:
-(void)newMessageReceived:(NSNotification *) notification
{
elapsedTime = [[notification object] intValue];
elapsedHours = elapsedTime / 3600;
elapsedTime = elapsedTime - (elapsedTime % 3600);
elapsedMinutes = elapsedTime / 60;
elapsedTime = elapsedTime - (elapsedTime % 60);
elapsedSeconds = elapsedTime;
secondInt = secondInt + elapsedSeconds;
if (secondInt > 59) {
++minuteInt;
secondInt -= 60;
}
minuteInt = minuteInt + elapsedMinutes;
if (minuteInt > 59) {
++hourInt;
minuteInt -= 60;
}
hourInt = hourInt + elapsedHours;
if (hourInt > 23) {
hourInt = 0;
}
}
The notification object is assigned to elapsedTime, but that is it; elapsedHours/minutes/seconds all stay at 0, and elapsedTime stays the same. Why isn't it working?
You are subtracting off the wrong part from elapsedTime. You should be subtracting the hours not the remainder:
or you could use the equivalent calculation: