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.
This is sample code for that:
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;
}
I am trying to write a similar application for Mac OS X and instead of a main loop i am using a simple timer:
- (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];
}
}
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.
Anyway, any ideas how to implement an application-wide timer on Cocoa (objective-c with Xcode)?
Thanks!
EDIT When using NSTimer this is the error I'm getting at runtime:
**[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.
EDIT 2
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:
MouseClick(1652) malloc: * error for object 0x1645c0: double free * set a breakpoint in malloc_error_break to debug
The freeing of the timer is done as follow:
[timer invalidate];
[timer release];
timer = nil;