GCD 使用总结(一) 介绍了 GCD 大概情况,现在看下在项目应用中,哪一些地方用到了 GCD 的能力.
1.延后加载 >>> dispatch_after
举例:在某些时候,我们加载一个 view, 希望用户注意到我们想要突出的部分,但是 view 上的东西太多,一起加载出现,用户很有可能会错过我们想要提醒的部分. 使用 dispatch_after 可以实现这个功能. dispatch_after能够延后执行代码. 将需要的 view 先加载出来, 在加载其他 view. 这样用户就能注意到我们想要提醒的部分了.UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(60, 60, 40, 40)];界面比较粗燥,但是不重要. 红色的方块先出现,然后在加载四个绿色的方块.
UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(60, 260, 40, 40)];
UIView *view3 = [[UIView alloc]initWithFrame:CGRectMake(160, 60, 40, 40)];
UIView *view4 = [[UIView alloc]initWithFrame:CGRectMake(160, 260, 40, 40)];
view1.backgroundColor = [UIColor greenColor];
view2.backgroundColor = [UIColor greenColor];
view3.backgroundColor = [UIColor greenColor];
view4.backgroundColor = [UIColor greenColor];
UIView *centerView = [[UIView alloc]initWithFrame:CGRectMake(110, 160, 40, 40)];
centerView.backgroundColor = [UIColor redColor];
double delayInSeconds = 2.0;
// dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); // 1
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ // 2
NSLog(@"当前线程:%@",[NSThread currentThread]);
[self addSubview:view1];
[self addSubview:view2];
[self addSubview:view3];
[self addSubview:view4];
});
NSLog(@"主线程:%@",[NSThread currentThread]);
[self addSubview:centerView];