Re: StopWatch Application Help
Re: StopWatch Application Help
- Subject: Re: StopWatch Application Help
- From: Marco Masser <email@hidden>
- Date: Sun, 20 Jul 2008 21:21:42 +0200
I'm trying to make a stopwatch application, and I'm having trouble
getting the Timer to fire, and then having the Text field being
updated.
Here's the code:
The essential part is missing: the method in which you are updating
your text field.
- (IBAction)startWatch:(id)sender
{
NSDate *currentDate = [NSDate date];
NSString *string = [timer value];
timer = [NSTimer timerWithTimeInterval:1 target:self
selector:@selector(startWatch:) userInfo:nil repeats: YES];
[timer isValid];
[textField setValue:string];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:
NSDefaultRunLoopMode];
[timer setFireDate:currentDate];
}
What you are doing is this: you create a timer and tell it to fire
every second (starting in one second), you add it to the default run
loops, then you tell it to fire "now". Every time the timer fires, it
is looking for a method with the signature - (void)startWatch:(NSTimer
*)timer. Again, read the docs for NSTimer and take a good look at what
the method should look like, whose selector you pass in.
Btw: the line [timer isValid] does nothing here.
The code should look like this (I write this in Mail, there may be
errors):
- (IBAction)startWatch:(id)sender {
[timer invalidate]; // Just in case the timer is already running
[timer autorelease];
// +scheduledTimer... methods do The Right Thing (TM) about run loops
in this case
timer = [NSTimer scheduledTimerWithInterval:1.0 target:self selector:
(updateTextfield:) userInfo:nil repeasts:YES];
[startTime autorelease];
startTime = [NSDate timeIntervalSinceReferenceDate]; // startTime is
of type NSTimeInterval here! Update your header file!
}
// This is the method the timer tries to call. Everything you want to
happen every second should be in here
- (void)updateTextfield:(NSTimer *)timer {
NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval difference = now - startTime;
NSString *timeString = [NSString stringWithFormat:@"%f", difference];
[textField setStringValue:timeString];
}
- (IBAction)stopWatch:(id)sender
{
[timer invalidate];
[timer release];
}
That's OK.
Hope this helps!
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden