Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

aznelementmaste

macrumors newbie
Original poster
Mar 24, 2008
23
0
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:
Code:
#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:

Code:
#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
 
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.