直接上代码:
四种方法有一些底层区别,后续有时间补给大家。
// 第一种不带参数
[self performSelector:@selector(yourFunction) withObject:nil afterDelay:1.0f];
// 带参数
[self performSelector:@selector(delayDo:) withObject:@"abc" afterDelay:1.0f];
// 第二种在主线程延迟
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)1*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
//此处写执行代码
});
// 第二种在子线程延迟
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//此处写执行代码
});
// 第三种会延迟当前线程状态,最好不要在主线程设置
[NSThread sleepForTimeInterval:1];
// 第四种
NSTimer * timer;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(delayDo:) userInfo:@"abc" repeats:YES];
NSTimer *timer1;
timer1 = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(aaa) userInfo:@"aaa" repeats:YES];
[timer setFireDate:[NSDate date]];
[timer fire];
[timer invalidate];