57211

How to get NSTimer to loop

Question:

I'm trying to learn about NSTimer, using Foundation and printing to the console. Can anybody tell me what I need to do to get the following to work? It compiles with no errors, but does not activate my startTimer method -- nothing prints.

My aim is to get one method to call another method to run some statements, and then stop after a set time.

#import <Foundation/Foundation.h> @interface MyTime : NSObject { NSTimer *timer; } - (void)startTimer; @end @implementation MyTime - (void)dealloc { [timer invalidate]; [super dealloc]; } - (void)startTimer { timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(runTimer:) userInfo:nil repeats:YES]; } - (void)runTimer:(NSTimer *)aTimer { NSLog(@"timer fired"); } @end int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; MyTime *timerTest = [[MyTime alloc] init]; [timerTest startTimer]; [timerTest release]; [pool release]; return 0; }

Answer1:

The timer never gets a chance to fire in your program, because the program ends almost immediately after the timer is created.

There's a construct called the <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html" rel="nofollow">Run Loop</a> which is responsible for processing input, including input from timers. One run loop is created for each thread, but it isn't automatically started in this case.

You need to run the run loop and keep it going until the timer has a chance to fire. Fortunately, this is quite easy. Insert:

[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5.0]];

between sending startTimer and release to timerTest. If you want the timer to repeat, you'll need to continue keeping the run loop active.

Note that you only need to do that in a simple program like this; when you are creating an application with a GUI, the run loop will be started via the Cocoa application setup process, and will remain active until the application terminates.

Answer2:

You have to add your timer to the default runloop after initializing it:

[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

Put this in -(void)startTimer.

Recommend

  • Getting SIGABRT signal when I try to play a video (Objective-C)
  • How to use dealloc when dealing with auto-synthesized properties?
  • picture does not show up using iCarousel
  • FPPopover won't pop up on button press, just NSLogs “FPPopoverController dealloc”
  • [ViewController gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:]: message sent
  • view will disappear is not firing
  • Cocoa: Crash in _NSDisplayOperationStack; Need Guidance
  • Viewcontroller Dealloc Method Never Gets Called
  • resignFirstResponder to UITextViews on UITableViewCells that are no longer on screen
  • ARC/ObjC++: C++ object inside an ObjC container
  • iPhone Development - Simulate Memory Warning
  • Exception System.InvalidCastException when calling a method bound with btouch that returns an object
  • Memory leak — setting variable in init?
  • Why won't a toast notification appear in my background Service (using System.Timer)?
  • Autorelease then retain for setters
  • Initial Form of C# program unavailable while the program is running
  • iOS Blocks Async Callbacks Causing Crash after View Controller is deallocated
  • NSOperationQueue becomes suspended at random?
  • VLC player event catch
  • Redis scan skipping keys
  • Chrome identity api to get profile info
  • Help with SimpleCursorAdapter and Listview
  • Stored data can't access in Yii
  • Spring MVC AccessDeniedException 500 error received instead of custom 401 error for @PreAuthorized u
  • “Member has private access error” after deleting plugin in CakePHP using PhpStorm
  • Expand header row into multiple child rows
  • Blocks within NSOperation
  • Why does Apple use assign rather than weak to store a delegate?
  • How to replace TouchesBegan with UIGestureRecognizer
  • how to remove a div with same ids but display='block' and display='none' in JAVa
  • Monotouch crashes with NullReferenceException on non nullable object
  • Jquery popup on mouse over of calendar control
  • QLPreviewController hide print button in ios6
  • Obtain ObjectIdHex value from mgo query
  • jquery mobile loadPage not working
  • How to include full .NET prerequisite for Wix Burn installer
  • NSLayoutConstraint that would pin a view to the bottom edge of a superview
  • Qt: Run a script BEFORE make
  • Bitwise OR returns boolean when one of operands is nil
  • Observable and ngFor in Angular 2