ios - Objective-C中另一个线程中的计时器

标签 ios objective-c nstimer nsrunloop nsblockoperation

我必须定义应该以一定时间间隔定期调用的方法。我需要在另一个线程(不是主线程)中调用它,因为此方法用于从外部 API 获取信息并同步核心数据中的数据。

如何定义此方法以不阻塞主线程?

最佳答案

除非您对计时器有特殊需求,否则您可以使用 Grand Central Dispatch。

以下代码段将在 2 秒后在默认优先级并发队列(即后台线程)上执行一个 block 。如果您认为合适,您可以更改队列的优先级,但除非您在并发队列上处理大量不同的操作,否则默认值就足够了。

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));

dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    // Your code here
});

如果你想重复调用它,那么你可以使用 dispatch_source_set_timer 来设置重复执行。它的要旨如下:

// Create a dispatch source that'll act as a timer on the concurrent queue
// You'll need to store this somewhere so you can suspend and remove it later on
dispatch_source_t dispatchSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
                                                          dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); 

// Setup params for creation of a recurring timer
double interval = 2.0;
dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, 0);
uint64_t intervalTime = (int64_t)(interval * NSEC_PER_SEC);
dispatch_source_set_timer(dispatchSource, startTime, intervalTime, 0);

// Attach the block you want to run on the timer fire
dispatch_source_set_event_handler(dispatchSource, ^{
    // Your code here
});

// Start the timer
dispatch_resume(dispatchSource);

// ----

// When you want to stop the timer, you need to suspend the source
dispatch_suspend(dispatchSource);

// If on iOS5 and/or using MRC, you'll need to release the source too
dispatch_release(dispatchSource);

关于ios - Objective-C中另一个线程中的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21563825/

相关文章:

ios - NSURLSessionDataTask 超时后续请求失败

ios - Objective-C . 追踪无法识别的选择器

objective-c - 将 NSString 添加到可变数组

objective-c - 如何委托(delegate) textStorageDidProcessEditing 通知?

objective-c - NSTimer 内存管理问题

swift - NSTimer 在后台绘制 barChart

swift - [__NSCFTimer copyWithZone :]: unrecognized selector sent to instance

iphone - #import <ChatKit/ChatKit.h> 文件不存在?

ios - 如何更改“在应用商店中”的字眼

ios - 带阴影的 UIView - 应用 renderInContext 时速度较慢