tags:

views:

50

answers:

2

I would like to create a time counter in my app that shows the user how many minutes the app has been running the current session and total. How do I create such time counter and how do I save the value to the phone? I'm new to app developement.

+1  A: 

You can use the NSDate and NSDateFormatter classes for this.

Here's an example:

Declare an NSDate instance in your .m file:

@implementation MyClass 

NSDate *startDate;
BOOL stopTimer = NO;
//...    

-(void) showElapsedTime: (NSTimer *) timer {
    if(!startDate) {
        startDate = [NSDate date]; 
    }
    NSTimeInterval timeSinceStart = [[NSDate date] timeIntervalSinceDate:startDate];
    NSDate *newDate = [[NSDate alloc] initWithTimeInterval:timeSinceStart sinceDate:startDate];
    NSString *dateString = [NSDateFormatter localizedStringFromDate:newDate dateStyle: NSDateFormatterNoStyle timeStyle: NSDateFormatterShortStyle];


    //do something with dateString....

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

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

//...

@end
Jacob Relkin
Thanks. how can I save this in iPhone's database? (save newDate on app exit)
Sam
See paul's comment.
Jacob Relkin
one last thing- how do I add two dates? newDate + totalDate
Sam
Try `NSDate *addedDate = [newDate dateByAddingTimeInterval:[newDate timeIntervalSinceDate:startDate]];`
Jacob Relkin
Do I need to use a loop to keep refreshing the time counter?
Sam
Yes. I'll edit my answer.
Jacob Relkin
thank you so much
Sam
@Sam, sure. Can you upvote please? ;)
Jacob Relkin
Sure. Trying to get NSUserDefaults to save data. It's not working. I put it viewDidUnload. Also, where should I load the data on app start.
Sam
`applicationDidFinishLaunching`.
Jacob Relkin
@Sam, catch me on AIM. My name lowercase without spaces.
Jacob Relkin
im online now. ran in to another problem. NSDate *startDate = [NSDate date]; //initializer element not a constant
Sam
@Sam, try it now.
Jacob Relkin
+1  A: 

On the iPhone you can use the API CFAbsoluteTimeGetCurrent() to get a numeric value for the current date and time. You can call this twice and subtract the two numbers from each other to get an elapsed time between those calls. You can then save that elapsed time between executions of your program to save the total time the user has had your program running.

fbrereto
how and where do I save the data? thx
Sam
The simplest way to store data is perhaps by using NSUserDefaults. You can then progress to using Core Data (for better flexibility) as your knowledge of the API increases.
paul_sns