美文网首页
iOS: 延缓执行的几种方法

iOS: 延缓执行的几种方法

作者: 一代枭雄 | 来源:发表于2021-10-13 16:47 被阅读0次

一. performSelector

/**

第一个参数:需要延迟执行的方法

第二个参数:要传入的参数(id类型)

第三个参数:延迟的时间

*/

[selfperformSelector:@selector(testMethod1:)withObject:@"aaa"afterDelay:1.0];

二. NSTimer

// 1.延迟执行某一段代码

NSTimer*timer=[NSTimer scheduledTimerWithTimeInterval:5.0repeats:NO block:^(NSTimer*_Nonnull timer){// 需要延迟执行的代码}];//

 2.延迟执行某一个方法

NSTimer*timer=[NSTimer scheduledTimerWithTimeInterval:5.0target:selfselector:@selector(testMethod1:)userInfo:nil repeats:NO];

// 如果使用上面两种延迟执行的方法,建议将定时器添加到NSRunLoop的Common模式中,防止其他控件的交互影响到定时器[[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];

// 取消定时器[timer invalidate];// 取消的同时要销毁定时器timer=nil;

三. NSThread

//该方法使当前线程进入休眠状态来达到延迟的目的// 只有一个参数:延迟的时间[NSThreadsleepForTimeInterval:1.0];

四. GCD

// 第一个参数:延迟的时间// 可以通过改变队列来改变线程dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(1.0*NSEC_PER_SEC)),dispatch_get_main_queue(),^{// 需要延迟执行的代码};

相关文章

网友评论

      本文标题:iOS: 延缓执行的几种方法

      本文链接:https://www.haomeiwen.com/subject/afheoltx.html