查看FBKVOController
時,看到 dispatch_source_t
創建的定時器,然後就網路上查閱資料了解了一下,大致步驟是:
1.創建調度源 dispatch_source_create(dispatch_source_type_t type, uintptr_t handle, unsigned long mask, dispatch_queue_t _Nullable queue);
- 設置計時器
dispatch_source_set_timer(dispatch_source_t source, dispatch_time_t start, uint64_t interval, uint64_t leeway);
3.設置給調度源 事件處理程序塊 dispatch_source_set_event_handler(dispatch_source_t source, dispatch_block_t _Nullable handler);
4.恢復啟用 dispatch_resume(dispatch_object_t object);
5.設置掛起計時器或者 取消調度源dispatch_source_cancel(dispatch_source_t source);
or dispatch_suspend(dispatch_object_t object);
注意:suspend狀態如果將計時器置為nil將會報錯,suspend後需要resume後方可 置為nil, 或者直接cancel,再將計時器置為nil
下方為示例代碼:
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, dispatch_time(DISPATCH_TIME_NOW, 0 *NSEC_PER_SEC), 1.0 * NSEC_PER_SEC, 0);
__block NSInteger i = 0;
__weak typeof(self) weakSelf = self;
dispatch_source_set_event_handler(_timer, ^{
i ++;
NSLog(@"次數 : %ld", (long)i);
if (i == 10) {
[weakSelf cancel];
}
});
dispatch_resume(_timer);
}
- (void)cancel {
dispatch_source_cancel(_timer);
_timer = nil;
NSLog(@"計時器銷毀");
}
以上是個人學習記錄,如果錯誤還請指正,謝謝。
网友评论