标签:
1.GCD应用 单例模式});
2.延迟操作
//1、
NSLog(@"开始执行");
// [self performSelector:@selector(handleAction) withObject:nil afterDelay:0];
//2、
//DISPATCH_TIME_NOW 从现在开始
//delayInSeconds 延迟几秒
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC));
// when dispatch_time_t
dispatch_after(time, dispatch_get_main_queue(), ^{
NSLog(@"%@",[NSThread currentThread]);
});
3.调度组
//创建调度组
dispatch_group_t group = dispatch_group_create();
//获取全局队列
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//调度组的异步请求
dispatch_group_async(group, queue, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"下载第一张图");
});
dispatch_group_async(group, queue, ^{
[NSThread sleepForTimeInterval:3];
NSLog(@"下载第二张图");
});
dispatch_group_async(group, queue, ^{
[NSThread sleepForTimeInterval:1];
NSLog(@"下载第三张图");
});
dispatch_group_async(group, queue, ^{
[NSThread sleepForTimeInterval:5];
NSLog(@"下载第四张图");
});
//notify通知,当所有异步请求完成时调用dispatch_group_notify
dispatch_group_notify(group, queue, ^{
NSLog(@"更新UI");
});
4.调度组的第二种方式
//创建调度组
dispatch_group_t group = dispatch_group_create();
//获取全局队列
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//进入队列
dispatch_group_enter(group);
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"下载第一张图");
//离开队列
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:1];
NSLog(@"下载第er张图");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:3];
NSLog(@"下载第san张图");
dispatch_group_leave(group);
});
//等待调度队列wait相当于一个阻塞状态 等最后一个异步进程执行后,更新UI才执行
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
NSLog(@"更新UI");
5.中断操作
//dispatch_barrier_async一定是自定义队列
//这里指定的并发队列应该是自己通过dispatch_queue_create函数创建的。如果你传的是一个串行队列或者全局并发队列,这个函数等同于dispatch_async函数。
dispatch_queue_t queue = dispatch_queue_create("com.blogcn", DISPATCH_QUEUE_CONCURRENT); //dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:1];
NSLog(@"1");
});
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:3];
NSLog(@"2");
});
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"3");
});
//中断操作dispatch_barrier_async
dispatch_barrier_async(queue, ^{
NSLog(@"--------");
[NSThread sleepForTimeInterval:1];
});
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:1];
NSLog(@"4");
});
dispatch_async(queue, ^{
NSLog(@"5");
});
6.遍历
//遍历操作
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//iterations 遍历的次数
dispatch_apply(5, queue, ^(size_t i) {
NSLog(@"%@",@(i));
});
标签:
原文地址:http://www.cnblogs.com/ldnh/p/5280929.html