GCD延时加载

这里我将为大家用两种方式来实现延时操作,分别是NSThread和GCD方式。并比较他们的优劣。

【使用NSThread实现延迟】

(1)拖入GCD源码。代码如下:

[objc]  view plain copy print ?
  1. #import "ViewController.h"  
  2. #import "GCD.h"  
  3.   
  4.   
  5. @interface ViewController ()  
  6.   
  7. @end  
  8.   
  9. @implementation ViewController  
  10.   
  11. - (void)viewDidLoad {  
  12.   [super viewDidLoad];  
  13.   
  14.   NSLog(@"开始启动");  
  15.     
  16.   //NSThread方式的延时执行操作;  
  17.   [self performSelector:@selector(threadEvent:)  
  18.              withObject:self  
  19.              afterDelay:2.f];  
  20.     
  21. }  
  22.   
  23. - (void)threadEvent:(id)sender{  
  24.   
  25.   NSLog(@"NSThread实现延时操作");  
  26.   
  27. }  
  28.   
  29. @end  

(2)运行效果如下:


(3)结果分析,可以从输出的时间上看到,后面的输出的确是延迟了2s。


【使用GCD实现延迟】

(1)代码实现如下:

[objc]  view plain copy print ?
  1. #import "ViewController.h"  
  2. #import "GCD.h"  
  3.   
  4.   
  5. @interface ViewController ()  
  6.   
  7. @end  
  8.   
  9. @implementation ViewController  
  10.   
  11. - (void)viewDidLoad {  
  12.   [super viewDidLoad];  
  13.   
  14.   NSLog(@"开始启动");  
  15.     
  16.     
  17.   //GCD方式实现延迟;  
  18.   //主线程;  
  19.   [GCDQueue executeInMainQueue:^{  
  20.     NSLog(@"GCD实现延迟操作");  
  21.   } afterDelaySecs:2.f];  
  22.     
  23. }  
  24.   
  25. @end  

(2)输出结果如下:

(3)结果分析:

可以看到,GCD也可以实现延迟操作。


       既然上述两种方式都能实现延迟,那么我们来比较一下优劣。

GCD的优点:

(1)代码简练,方便。


GCD的缺点:

(1)延迟时间的精确度较低。下面是我同时进行延迟操作,GCD误差较大:


(2)NSThread可以在开始延迟后取消,但是GCD不能。NSThread取消延迟的代码:

[objc]  view plain copy print ?
  1. [NSObject cancelPreviousPerformRequestsWithTarget:self];  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值