bkbeachlabs
bkbeachlabs

Reputation: 2171

creating a timer for a level in iphone game

Im trying to add a timer to my game so that the user knows how long they have spent playing a level. Ive figured out that I can initialize a timer the following way:

bool showTimer = YES;
NSDate startDate;
UILabel timerLabel; // initialized in viewDidLoad

    -(void) showElapsedTime: (NSTimer *) timer {
        if (showTimer) {
            NSTimeInterval timeSinceStart;

            if(!startDate) {
                startDate = [NSDate date]; 
            }

            timeSinceStart = [[NSDate date] timeIntervalSinceDate:startDate];
            NSString *intervalString = [NSString stringWithFormat:@"%.0f",timeSinceStart];
            timerLabel.text = intervalString;

            if(stopTimer) {//base case
                [timer invalidate];
            }
        }
    }

    - (void) startPolling {
        [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(showElapsedTime:) userInfo:nil repeats:YES];
    }

I start the startPolling method in the viewDidLoad. When I run the app, I do see the timer and it tracks the time but when I exit the app and re-enter it, the timer doesnt pause. I'm also not sure how to handle going to another view (like the options menu) and then coming back to this view. I understand NSDefaults and NSCoding and I see how I could save the current value on the timer as a Coding object, keeping a seperate key-value pair in a plist for every level but this seems cumbersome.

Is there a better way to keep track of how long the user spends in a level?

Upvotes: 0

Views: 451

Answers (1)

lnafziger
lnafziger

Reputation: 25740

Instead of doing the calculation (subtracting the start time from the current time) every time, since all you care about is an elapsed time, just have a variable like NSTimeInterval elapsedTime that you start at 0 and add time to every time that the timer fires. (If you want to track it to 0.1 seconds like in your example, just divide by 10 before displaying it.) This way, you can pause it whenever you want and it will just continue on from where it was before when it starts up again.

Upvotes: 1

Related Questions