1.在主线程中延迟执行某动作,不会卡主主线程,不影响后面的东做执行
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(@"%@", [NSThread currentThread]);
});
2.在子线程中执行某动作,不会卡主整个线程
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(@"%@", [NSThread currentThread]);
});
3.实现延迟,该线程本身在哪个线程中就再哪个线程中执行
NSURL *url = [NSURL URLWithString:@"http://59320.jpg.com"];
[self performSelector:@selector(download:) withObject:url afterDelay:3];
4.利用sleep实现延迟(不要用这个,会卡住主线程,即后面的动作不会执行)
[NSThread sleepForTimeInterval:3];
5.NSTimer定时器
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
注:此方法是一种非阻塞的执行方式,
取消执行方法:- (void)invalidate;即可