1. GCD延時執(zhí)行
1.1 延時執(zhí)行常用的方法有2種
分別是 performSelector 和NSTimer
- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
其中 performSelector的用法
[self performSelector:@selector(test) withObject:nil afterDelay:2.0];
其中 NSTimer的用法
/*
第一參數(shù):延遲的時間,也就是多少秒后執(zhí)行
第二參數(shù):指定一個對象發(fā)送,通常是當(dāng)前界面,self
第三參數(shù):調(diào)用的函數(shù)
第四參數(shù):計時器的用戶信息
第五參數(shù):YES,就會循環(huán)執(zhí)行,直至失效。NO,只會執(zhí)行一次
*/
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:NO];
1.2 GCD延時執(zhí)行的方法
// 主隊列
// dispatch_queue_t queue = dispatch_get_main_queue();
// 開線程
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
/*
第一參數(shù): DISPATCH_TIME_NOW 從現(xiàn)在開始計算時間
第二參數(shù)(delayInSeconds): 要延遲的時間 2.0 GCD時間單位:納秒
第三參數(shù)(dispatch_get_main_queue): 主隊列
第四參數(shù)^{ }:寫需要執(zhí)行的代碼
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), queue, ^{
NSLog(@"GCD------%@",[NSThread currentThread]);
});
2. GCD一次性代碼
- 作用:一次性代碼:整個應(yīng)用程序運行過程中只會被執(zhí)行一次 不能放在懶加載中,應(yīng)用場景:單例模式
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"----once-----");
});
3. GCD知識點補充
- GCD中的定時器
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 1.創(chuàng)建GCD中的定時器
/*
第一參數(shù)(DISPATCH_SOURCE_TYPE_TIMER): source 的類型 DISPATCH_SOURCE_TYPE_TIMER 表示是定時器
第二參數(shù)(0): 描述信息,線程ID
第三參數(shù)(0): 更詳細(xì)的描述信息
第四參數(shù)(<#dispatchQueue#>): 隊列,決定GCD定時器中的任務(wù)在哪個線程中執(zhí)行
*/
// 注意:需要strong 強引用后才能運行使用,不強引用運行期間可能會被釋放掉
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
// 2. 設(shè)置定時器(起始時間 | 間隔時間 | 精準(zhǔn)度)
/*
第一參數(shù)(timer): 創(chuàng)建的定時器對象
第二參數(shù)(DISPATCH_TIME_NOW): 起始時間, DISPATCH_TIME_NOW 從現(xiàn)在開始計時
第三參數(shù)(<#intervalInSeconds#> * NSEC_PER_SEC): 間隔時間,2.0 --- GCD 中時間單位是納秒,
第四參數(shù)(<#leewayInSeconds#> * NSEC_PER_SEC): 精準(zhǔn)度 絕對精準(zhǔn) 0
*/
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
// 3. 設(shè)置定時器執(zhí)行的任務(wù) - 通過block塊的方式操作
dispatch_source_set_event_handler(timer, ^{
NSLog(@"GCD --- %@",[NSThread currentThread]);
});
// 4.啟動執(zhí)行
dispatch_resume(timer);
self.timer = timer;
// 啟動程序,不執(zhí)行的原因:是因為2秒后timer被釋放