PDA

View Full Version : NSTimeInterval, and application help!




aznelementmaste
Jul 20, 2008, 04:10 PM
I'm currently writing a Stopwatch application so that I can better understand NSTimer, and NSTimeInterval.

I've written the code, but, however, it starts from January 1, instead of the current date (i want it to so that the text field is updated every second, and displays it going from 0, instead from January 1st).

Can Anyone please help?

Here's the Code:


AppController.h:


#import <Cocoa/Cocoa.h>


@interface AppController : NSObject {
IBOutlet NSTextField *textField;
NSTimer *timer;
}

- (IBAction)startWatch:(id)sender;
- (IBAction)stopWatch:(id)sender;
- (IBAction)resetWatch:(id)sender;

@end


AppController.m:

#import "AppController.h"


@implementation AppController

- (void)awakeFromNib
{
[textField setStringValue:@" "];
}

- (IBAction)startWatch:(id)sender
{
NSDate *currentDate = [NSDate date];
timer = [NSTimer timerWithTimeInterval:0 target:self selector:@selector(updateTextfield:) userInfo:nil repeats: YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode: NSDefaultRunLoopMode];
[timer setFireDate:currentDate];
[timer retain];

NSGarbageCollector *collector = [NSGarbageCollector defaultCollector];
[collector collectIfNeeded];
}

- (void)updateTextfield:(NSTimer *)timer {

NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval startTime;

NSTimeInterval difference = now - startTime;

NSString *timeString = [NSString stringWithFormat:@"%f", difference];
[textField setStringValue:timeString];

NSGarbageCollector *collector = [NSGarbageCollector defaultCollector];
[collector collectIfNeeded];
}

- (IBAction)resetWatch:(id)sender
{
[textField setStringValue:@" "];

NSGarbageCollector *collector = [NSGarbageCollector defaultCollector];
[collector collectIfNeeded];
}

- (IBAction)stopWatch:(id)sender
{
[timer invalidate];

NSGarbageCollector *collector = [NSGarbageCollector defaultCollector];
[collector collectIfNeeded];
}

@end


Thanks for any help! :D



Catfish_Man
Jul 20, 2008, 04:37 PM
NSTimeInterval isn't initialized to the current time by default, so startTime is probably not set to what you want. Also, leave out the garbage collector stuff. It's pretty smart, it'll handle it.