//用GCD做計時器 精確時間
NSTimeInterval period = 1.0; //設(shè)置時間間隔
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒執(zhí)行
dispatch_source_set_event_handler(_timer, ^{
//在這里執(zhí)行事件
dispatch_sync(dispatch_get_main_queue(), ^{
});
});
暫停計時器
dispatch_resume(_timer);//恢復(fù)計時器,啟動也是這個
dispatch_suspend(_timer);//暫時掛起,掛起的時候_timer不能被釋放,否則會崩潰
dispatch_source_cancel(_timer);//停止計時器,停止以后就可以釋放_timer了
說明一下:
1._timer在掛起以后,之前的計時仍然有效,比如你在計時到0.9秒的時候掛起,再次resume的時候就從0.9開始計算,過了0.1秒以后就會執(zhí)行handler里的block。
2.dispatch_walltime 表示用精準計時,不跟隨系統(tǒng),不受系統(tǒng)的后臺狀態(tài)影響。
3.dispatch_source_set_event_handler是在子線程執(zhí)行的,有UI刷新的代碼需要調(diào)換到dispatch_get_main_queue()里執(zhí)行。