直接上代码:
四种方法有一些底层区别,后续有时间补给大家。
// 第一种不带参数
[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];
这篇博客详细介绍了在iOS开发中实现延迟执行的四种方法:使用`performSelector:withObject:afterDelay:`、 dispatch_after、`NSThread.sleepForTimeInterval:`以及`NSTimer`。这些方法各有特点,适用于不同的场景,例如在主线程或子线程延迟执行,以及是否需要传参等。
1214

被折叠的 条评论
为什么被折叠?



