Re: NSTimer does NOT repeat, why ?
Re: NSTimer does NOT repeat, why ?
- Subject: Re: NSTimer does NOT repeat, why ?
- From: Jason Coco <email@hidden>
- Date: Thu, 18 Sep 2008 05:32:51 -0400
On Sep 18, 2008, at 05:18 , Florian Soenens wrote:
Hi list,
anyone knows why in this simple piece of code, the method testTimer
is only called once and not every 2 seconds?
Yes, it is because you created a timer and then fired it manually. You
need to schedule the timer with the run loop
in order to get it to fire repeatedly... the run loop is what is
responsible for firing your timer every x seconds. You can
also adjust this if you don't actually need a reference to the timer
(I assume you're keeping one because you may
have to fire it manually from time to time, or you may want to
invalidate it outside of its normal cycle and call-back).
The example below schedules the timer automatically during
awakeFromNib (I'm assuming that this is the functionality
that you want based on your example). You could also create the timer
and schedule it manually with the run loop (e.g.,
in response to a button press). For further reference, you should see
the documentation for NSTimer and NSRunLoop... links provided
at the bottom of this message for reference. It's important to note
that a timer will never fire automatically unless it's scheduled
with a run loop and that run loop is running in the correct mode.
HTH, Jason
Replace your implementation with this:
#import "Controller.h"
@implementation Controller
-(void)awakeFromNib
{
NSLog(@"Creating NSTimer");
timer = [[NSTimer scheduledTimerWithTimeInterval:2.0 target:self
selector:@selector(testTimer:) userInfo:nil repeats:YES] retain];
// do you really want to fire it manually right away? if so, leave
this line here - this will not interrupt the regular schedule
[timer fire];
}
-(void)testTimer:(NSTimer*)aTimer
{
NSLog(@"Fired: %@", aTimer);
}
@end
NSTimer: http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html
NSRunLoop: http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
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