- 执行一次代码
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"only once")
});
- 延迟执行
- 主线程睡眠3秒,该方法不推荐,因为会阻塞主线程,影响用户体验
[NSThread sleepForTimeInterval:3.0];
- 该方法在哪个线程中调用则延迟执行的方法也会在哪个方法中执行,即过设定的时间后会重新回到该线程中执行方法
[self performSelector:@selector(download:) withObject:@"http://beautifulImage.jpg" afterDelay:2.0];
-(void)download:(NSString *)image {}
- 将GCD延迟执行操作放到主队列中执行
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"after tow seconds");
});
将GCD延迟执行操作放到全局并发队列中执行
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), queue, ^{
NSLog(@"after tow seconds");
});
网友评论