Objective-C 中计时器设置与取消

考察这样的场景:进入页面后设置接口轮询更新数据,离开页面时清除掉计时器。

轮询可通过创建延时任务,并且在任务中递归调用自己来生成。Objective-C 中延时任务有多种方式,配合 viewDidLoadviewWillDisappear 实现计时器的设置与清除。

performSelector:withObject:afterDelay:cancelPreviousPerformRequestsWithTarget:

通过 NSObject 上的 performSelector:withObject:afterDelay: 配合 cancelPreviousPerformRequestsWithTarget:

[NSObject performSelector:@selector(SampleMethod) withObject:self afterDelay:delayTime];
[NSObject cancelPreviousPerformRequestsWithTarget:self];

dispatch_afterdispatch_block_cancel

通过 dispatch_afterdispatch_block_cancel 实现任务延迟与取消。

声明一个变量保存需要执行的任务:

var block: dispatch_block_t?

初始化 block 然后通过 dispatch_after 触发:

block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) {
  print("I executed")
}
let time: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(5 * NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue(), block!)

最后在合适的时机通过 dispatch_block_cancel 取消任务:

dispatch_block_cancel(block!)

DispatchWorkItem

Swift 中可使用 DispatchWorkItemcancel()

let queue = DispatchQueue(label: "queue", attributes: .concurrent)
let workItem = DispatchWorkItem {
    print("done")
}
    
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
    queue.async(execute: workItem) // not work
}
workItem.cancel()

相关资源