作为 NSTimer 的替代方案,在 iOS 4.0+ 和 10.6+ 上,您可以使用 Grand Central Dispatch 和调度源使用块来执行此操作。Apple 在他们的并发编程指南中有以下代码:
dispatch_source_t CreateDispatchTimer(uint64_t interval, uint64_t leeway, dispatch_queue_t queue, dispatch_block_t block)
{
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
if (timer)
{
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval, leeway);
dispatch_source_set_event_handler(timer, block);
dispatch_resume(timer);
}
return timer;
}
然后,您可以使用如下代码设置一秒计时器事件:
dispatch_source_t newTimer = CreateDispatchTimer(1ull * NSEC_PER_SEC, (1ull * NSEC_PER_SEC) / 10, dispatch_get_main_queue(), ^{
[self setX:someValue andY:otherValue andObject:obj];
});
只要您在完成后存储并释放计时器。这甚至可以让您通过使用并发队列而不是上面使用的主队列来触发计时器以在后台线程上执行项目。
这可以避免装箱和拆箱参数的需要。