iOS 之 延迟操作

2022-06-30  本文已影响0人  小羊爱学习

1.performSelector方法
此方式要求必须在主线程中执行,否则无效。是一种非阻塞的执行方式,暂时未找到取消执行的方法。

[self performSelector:@selector(delayMethod) withObject:nil afterDelay:1.0f];

2.定时器:NSTimer
此方式要求必须在主线程中执行,否则无效。是一种非阻塞的执行方式,可以通过NSTimer类的- (void)invalidate;取消执行。

[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(delayFun) userInfo:nil repeats:NO];

3. sleep方式
此方式在主线程和子线程中均可执行。是一种阻塞的执行方式,建义放到子线程中,以免卡住界面没有找到取消执行的方法。

[NSThread sleepForTimeInterval:1.0f]; [self delayMethod];

4.GCD方式
此方式在可以在参数中选择执行的线程。是一种非阻塞的执行方式,没有找到取消执行的方法。

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
 
        NSLog(@"延迟2秒执行--%@",[NSThread currentThread]);
 
});
上一篇 下一篇

猜你喜欢

热点阅读