Men的博客

欢迎光临!

0%

GCD

什么是GCD

Grand Central Dispach–
好用:1.简单
基于block c函数接口
功能强大:支持多核心编程
支持高级编程功能

创建和使用

dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

创建和使用

//开启一个新的线程
//queue
//三种:main——queue主线程队列
//globle——queue全局队列。异步任务加载这里
//自定义的
dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
for (int i=0; i<100; i++)
{
NSLog(@”A=%d”,i);
}
});
dispatch_async(queue, ^{
for (int i=0; i<100; i++)
{
NSLog(@”B=%d”,i);
}
});

模拟网络数据下载

[self simulaterNetworkDataDownload];

延迟执行,延时5s执行

[self delayRunCode];

有的代码指向执行一次

[self runOneCode];
[self runOneCode];
[self runOneCode];
[self runOneCode];

多个任务同时执行,等待所有任务结束

// 模拟迅雷多路下载后关机
[self simulaterThreadDownload];

}
-(void)simulaterThreadDownload
{
dispatch_group_t group=dispatch_group_create();

//任务添加
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i=0; i<30; i++)
{
NSLog(@” B=%d”,i);
[NSThread sleepForTimeInterval:0.1];
}
});
//先是所有任务执行完成
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@”所有的任务执行完成”);
});
}
-(void)runOneCode
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@”这句话我只说一次”);
});
}
-(void)delayRunCode
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@”我是一只小小小小鸟,永远永远也飞不高”);
});

}
-(void)simulaterNetworkDataDownload
{
_progressView=[[UIProgressView alloc]initWithFrame:CGRectMake(10, 100, 300, 20)];
[self.view addSubview:_progressView];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i=0; i<100; i++)
{
注意:不要再主线程里更新UI
// _progressView.progress+=0.01;

dispatch_async(dispatch_get_main_queue(), ^{
_progressView.progress+=0.01;
});
[NSThread sleepForTimeInterval:0.1];
}
NSLog(@”下载完成”);
});

}