- (void)delay1 { // 延遲執行不要用sleep,壞處:卡住當前線程 [NSThread sleepForTimeInterval:3]; NSLog(@"-----下載圖片-----"); }
- (void)delay2 { // 一旦定製好延遲任務後,不會卡主當前線程(延時任務在哪條線程執行取決於當前代碼在何處調用) [self performSelector:@selector(download:) withObject:@"http://555.jpg" afterDelay:3]; }
- (void)delay3 { // 3秒後回到主線程執行block中的代碼 // dispatch_queue_t queue = dispatch_get_main_queue(); // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), queue, ^{ // NSLog(@"------task------%@", [NSThread currentThread]); // }); // 3秒後自動開啓新線程 執行block中的代碼(也就是說會幫你開啓一條新的線程,延時一段時間以後執行block中的代碼) dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), queue, ^{ NSLog(@"------task------%@", [NSThread currentThread]); }); }