GCD的学习

2016-12-16  本文已影响17人  生活本无度

一、任务和队列

1.同步任务  dispatch_sync  不可以开启新线程

dispatch_queue_tqueue =dispatch_queue_create("123",DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^{

dispatch_sync(dispatch_get_main_queue(), ^{

//同步

});

});

2.异步任务 dispatch_async 可以开启新的线程

dispatch_queue_tqueue =dispatch_queue_create("123",DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^{

dispatch_async(dispatch_get_main_queue(), ^{

//异步

});

});

//主线程主队列+同步任务会造成死锁的现象切记不能再主队列里面添加同步任务

dispatch_sync(_queue,^{

dispatch_sync(_queue,^{

//do something

});

})

二、GCD的应用

1-》用于加载图片

dispatch_queue_tqueue =dispatch_queue_create("123",DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^{

NSData*date = [NSDatadataWithContentsOfURL:[NSURLURLWithString:@""]];

UIImage*image = [UIImageimageWithData:date];

dispatch_async(dispatch_get_main_queue(), ^{

//异步

UIImageView*imagesView = [UIImageViewnew];

imagesView.image= image;

});

});

2-》可以用于延时加载

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

//延时加载

UIImageView*imagesView = [UIImageViewnew];

imagesView.image= [UIImageimageNamed:@""];

});

3-》可以用于 按秩序 执行代码

dispatch_group_tgroup =dispatch_group_create();

dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

NSLog(@"11111");

});

dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

NSLog(@"22222");

});

dispatch_group_notify(group,dispatch_get_main_queue(), ^{

//在前面两个任务执行完后发送通知执行3333

NSLog(@"3333");

});

4-》 执行一次的代码 比如单例的创建 和 引导页

单例:(也可以用加锁的方式创建)

staticMyViewController*viewVC =nil;

staticdispatch_once_tonceToken;

dispatch_once(&onceToken, ^{

viewVC = [[[selfclass]alloc]init]; //只执行一次

});

5-》多次执行 某段代码

dispatch_apply(10,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^(size_t index) { //index 指的是下标

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

});//多次执行

上一篇下一篇

猜你喜欢

热点阅读