在 X11 下的 Linux 上并使用 GTK+,你有一个叫做“主循环”的东西。启动主循环后,您将拥有一个在应用程序的主线程中运行的计时器。您可以将该计时器设置为回调函数,并且您有一个非常好的应用程序范围的计时器。
这是示例代码:
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;
}
我正在尝试为 Mac OS X 编写一个类似的应用程序,而不是主循环,我使用的是一个简单的计时器:
- (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];
}
}
这似乎不太好用。计时器一直处于关闭状态。我也尝试过使用 NSTimer 但没有运气。我对objective-c 不是很熟悉,尤其是对GUI 应用程序。
无论如何,任何想法如何在 Cocoa (objective-c with Xcode) 上实现应用程序范围的计时器?
谢谢!
编辑 使用 NSTimer 时,这是我在运行时遇到的错误:
**[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.
编辑 2
好,我知道了。问题是我没有向计时器添加“目标:”。现在,当我关闭计时器时,出现以下错误:
MouseClick(1652) malloc: * error for object 0x1645c0: double free * set a breakpoint in malloc_error_break to debug
定时器的释放如下:
[timer invalidate];
[timer release];
timer = nil;