gcd

GCD

异步请求,我只认准 GCD | GCD异步,你值得拥有 (广告先走一波)

网络请求放在子线程,UI 只能在主线程更新

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {

// 处理各种耗时间的事情,比如网络请求数据,天知道要什么时候才能结束

dispatch_async(dispatch_get_main_queue(), ^(void) {

// 好了以后,我们回到主线程进行界面刷新

});

});

只执行一次

Xcode 自带的代码块

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

});

延迟执行

Xcode 自带的代码块

double delaySeconds = 5.0;

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delaySeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

});

创建队列

dispatch_queue_t baidu_queue = dispatch_queue_create("baidu.com", NULL);

dispatch_async(baidu_queue, ^{

NSLog(@"开启异步任务");

});

dispatch_sync(baidu_queue, ^{

NSLog(@"开启同步任务");

});

//----------------------------------

//执行10次,每次执行都开新进程,所以顺序不一定

dispatch_apply(10, DISPATCH_QUEUE_PRIORITY_DEFAULT, ^(size_t index) {

NSLog(@"index = %ld",index);

});

/-----------------------------------

任务组

// 多个任务(在多个线程)同时执行,等他们完成以后,再执行其他任务

//先建立一个分组,多个任务形成一个组,在组里面的任务完成以后再执行后续的任务

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, queue, ^{

NSLog(@"1");

});

dispatch_group_async(group, queue, ^{

NSLog(@"2");

});

dispatch_group_async(group, queue, ^{

NSLog(@"3");

});

dispatch_group_async(group, queue, ^{

NSLog(@"4");

});

dispatch_group_async(group, queue, ^{

NSLog(@"5");

});

dispatch_group_notify(group, dispatch_get_main_queue(), ^{

NSLog(@"主线程");

});

你可能感兴趣的:(gcd)