整理节点信息:
iOS Version : 10.3
Xcode : 8.3
一.不阻塞延时执行performSelector
[self performSelector:@selector(nothing) withObject:nil afterDelay:2];
NSLog(@"start delay");then
- (void)nothing{
NSLog(@"end delay");
}这里有一点要注意,在使用 performSelector 和代理调用这样的方法的时候,最好再加上 respondesToSelector 这样的方法来检测方法是否被实现,因为 performSelector 并不会在编译的时候检测方法是否被实现。
二.利用 GCD 不阻塞延时
NSLog(@"start");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*2), dispatch_get_main_queue(), ^{
NSLog(@"end");
});
GCD 的重复定时执行:待整理
三.NSThread阻塞延时
[NSThread sleepForTimeInterval:3];
四.NSTimer 定时执行
[NSTimer scheduledTimerWithTimeInterval:2 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"test");
}];这样 timer 会被自动加入到默认的 RunLoop 中,当然也可以自己手动加入。
timer 的释放:
[timer invalidate];
本文介绍了在iOS开发中常用的几种延时与定时方法,包括使用performSelector进行不阻塞延时执行、利用GCD(Grand Central Dispatch)实现不阻塞的延时任务、通过NSThread实现阻塞延时、以及利用NSTimer进行定时任务。每种方法都有其适用场景和注意事项。
2150

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



