iOS 4以降をターゲットにしている場合は、GrandCentralDispatchを使用できます。
// Set the time, '33333333' nanoseconds in the future (33.333333ms)
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 33333333);
// Schedule our code to run
dispatch_after(time, dispatch_get_main_queue(), ^{
// your code to run here...
});
これにより、33.333333ms後にそのコードが呼び出されます。これがループソート取引になる場合はdispatch_after_f
、ブロックの代わりに関数ポインターを使用する代わりに関数を使用することをお勧めします。
void DoWork(void *context);
void ScheduleWork() {
// Set the time, '33333333' nanoseconds in the future (33.333333ms)
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 33333333);
// Schedule our 'DoWork' function to run
// Here I pass in NULL for the 'context', whatever you set that to will
// get passed to the DoWork function
dispatch_after_f(time, dispatch_get_main_queue(), NULL, &DoWork);
}
void DoWork(void *context) {
// ...
// Do your work here, updating an on screen counter or something
// ...
// Schedule our DoWork function again, maybe add an if statement
// so it eventually stops
ScheduleWork();
}
そしてScheduleWork();
、タイマーを開始したいときに電話するだけです。繰り返しループの場合、これは上記のブロック方式よりも少しクリーンだと個人的には思いますが、1回限りのタスクでは、ブロック方式の方が間違いなく好きです。
詳細については、GrandCentralDispatchのドキュメントをご覧ください。