NSTimeInterval, and application help!

Discussion in 'Mac Programming' started by aznelementmaste, Jul 20, 2008.

  1. aznelementmaste macrumors newbie

    Joined:
    Mar 24, 2008
    #1
    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
     
  2. Catfish_Man macrumors 68030

    Catfish_Man

    Joined:
    Sep 13, 2001
    Location:
    Portland, OR
    #2
    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.
     

Share This Page