X11 で GTK+ を使用する Linux では、「メイン ループ」と呼ばれるものがあります。メイン ループを開始すると、アプリケーションのメイン スレッドで実行されるタイマーが作成されます。そのタイマーをコールバック関数に設定すると、非常に優れたアプリケーション全体のタイマーが得られます。
これはそのためのサンプルコードです:
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 (Xcode を使用した object-c) でアプリケーション全体のタイマーを実装する方法はありますか?
ありがとう!
編集 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
はい、分かりました。問題は、タイマーに「target:」を追加しなかったことです。今、タイマーをオフにすると、次のエラーが表示されます。
MouseClick(1652) malloc: * error for object 0x1645c0: double free * set a breakpoint in malloc_error_break to debug
タイマーの解放は次のように行われます。
[timer invalidate];
[timer release];
timer = nil;