title: Do Cocoa applications have a main loop?
body: <p>On Linux under X11 and using GTK+ you have something called "Main Loop". Once you start the main loop you have a timer that runs in the main thread of the application. You can set that timer to a callback function and you have a very nice application-wide timer.</p>
  
  <p>This is sample code for that:</p>
  
  <pre><code>GMainLoop *loop;
  
  if(!loop_running)
  {
        display = XOpenDisplay( NULL );
        loop = g_main_loop_new(NULL, FALSE);
        g_timeout_add(1000, (GSourceFunc)callback, NULL); //1 sec laps   
        g_main_loop_run(loop);  //to stop use g_main_loop_quit ()  with the "loop" as arg
        loop_running=1;
  }
  </code></pre>
  
  <p>I am trying to write a similar application for Mac OS X and instead of a main loop i am using a simple timer:</p>
  
  <pre><code>- (void) handleTimer: (NSTimer *) timer
  {
      CopyDataToDB();
  } // handleTimer
  
  - (IBAction)startStopAction:(id)sender
  {
  
     isOn=!isOn;
     if(isOn)
     {
         // Add our timers to the EventTracking loop       
         [[NSRunLoop currentRunLoop] addTimer: time forMode: NSEventTrackingRunLoopMode];
  
         // Add our timers to the ModelPanel loop       
         [[NSRunLoop currentRunLoop] addTimer: time forMode: NSModalPanelRunLoopMode];
     }
     else
     {
         [timer invalidate];
     }
  
  }
  </code></pre>
  
  <p>That doesn't seem to work very well. The timer is set off all the time. I tried also with an NSTimer but no luck.
  I'm not very familiar with objective-c and specially with GUI applications.</p>
  
  <p>Anyway, any ideas how to implement an application-wide timer on Cocoa (objective-c with Xcode)?</p>
  
  <p>Thanks!</p>
  
  <p><strong>EDIT</strong>
  When using NSTimer this is the error I'm getting at runtime:</p>
  
  <pre><code>**[Session started at 2009-07-12 16:49:59 -0400.]
  2009-07-12 16:50:02.784 MouseClick[1490:10b] Starting
  2009-07-12 16:50:02.786 MouseClick[1490:10b] *** +[NSTimer scheduledTimerWithTimeInterval:selector:userInfo:repeats:]: unrecognized selector sent to class 0xa08d54c0
  2009-07-12 16:50:02.787 MouseClick[1490:10b] *** +[NSTimer scheduledTimerWithTimeInterval:selector:userInfo:repeats:]: unrecognized selector sent to class 0xa08d54c0**
  
  The Debugger has exited with status 0.
  </code></pre>
  
  <p><strong>EDIT 2</strong></p>
  
  <p>ok, i got it. The problem was that i didn't add a "target:" to the timer. now, when I'm shutting the timer off I am getting the following error: </p>
  
  <pre><code>MouseClick(1652) malloc: * error for object 0x1645c0: double free * set a breakpoint in malloc_error_break to debug 
  </code></pre>
  
  <p>The freeing of the timer is done as follow: </p>
  
  <pre><code>[timer invalidate]; 
  [timer release]; 
  timer = nil;
  </code></pre>