多线程学习11-GCD常用函数

学习多线程11(之前跟着小码哥视频学习了多线程,准备把学到的东西放到网上,便于参考。仅有视频,所以所有文字都是自己打的,同时也温习一下多线程)

GCD常用函数

iOS延迟常用的方法:

1;调用NSObject方法

[selfperformSelector:@selector(run)withObject:nilafterDelay:2.0];

2;GCD方法

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

        NSLog(@"2秒以后做的事情");

    });

3;NSTimer方法

[NSTimerscheduledTimerWithTimeInterval:2.0target:selfselector:@selector(run)userInfo:nilrepeats:NO];

一次性代码:

使用Dispatch_once函数能保证某段代码在程序运行过程中只被执行1次。

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        //只执行1次的代码(保证线程安全的)

    });

GCD组队列
下载图片/合成图片

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    
    //1.下载图片1
    dispatch_group_async(group, queue, ^{
        //图片的url
        NSURL *url = [NSURL URLWithString:@"http://img.pusa123.com/www/uploads/allimg/160315/17592_160315095042_1.jpg"];
        //加载图片
        NSData *data = [NSData dataWithContentsOfURL:url];
        //生成图片
        self.image1 = [UIImage imageWithData:data];
    });
   
    //2.下载图片2
    dispatch_group_async(group, queue, ^{
        //图片的url
        NSURL *url = [NSURL URLWithString:@"http://img4.duitang.com/uploads/item/201309/04/20130904205551_tfTyB.jpeg"];
        //加载图片
        NSData *data = [NSData dataWithContentsOfURL:url];
        //生成图片
        self.image2 = [UIImage imageWithData:data];
    });
    

    //3.将图片合成
    dispatch_group_notify(group, queue, ^{
        //开启新的图形上下文
        UIGraphicsBeginImageContext(CGSizeMake(100,100));
        //绘制图片
        [self.image1 drawInRect:CGRectMake(0, 0, 50, 100)];
        [self.image2 drawInRect:CGRectMake(50, 0, 50, 100)];
        
        //取得上下文中的图片
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        //结束上下文
        UIGraphicsEndImageContext();
        //回到主线程显示图片
        [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
    });
    
}


你可能感兴趣的:(多线程,ios,ios开发)