iosGCD基础用法

困死了,更完就睡。运行一下有福利,懂的。我这里就不上传效果图了,大家自己运行哈。。。晚安



#import "ViewController.h"


@interface ViewController ()

{

    

    UIImageView *_view;

}

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];


    

    //主队列是和主线程关联的一个队列,主队列是GCD提供的一个特殊队列, 添加到主队列中的任务,会在主线程中执行。 注意: 往主队列中加任务,不管是同步的方式还是异步的方式,都不会创建线程。

    //    dispatch_get_main_queue(); 取到主队列的方法

    

    // 开启子线程调用test方法

    [self performSelectorInBackground:@selector(test) withObject:nil];

    

    

    _view = [[UIImageView alloc]init];

    _view.frame = CGRectMake(0, 0, self.view.bounds.size.width, 300);

    [self.view addSubview:_view];

    

    

    

}


-(void)test

{

    

    dispatch_queue_t queue = dispatch_queue_create("Concurrent Queue", DISPATCH_QUEUE_CONCURRENT);

    

    dispatch_async(queue, ^{

        NSLog(@"222 curThread = %@",[NSThread currentThread]);

    });

    

    

    dispatch_sync(queue, ^{

        NSLog(@"333  cureThread = %@",[NSThread currentThread]);

    });

    

}




//用户点击屏幕,从网络上下载一张图片,显示到界面上

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    

    // 1. 取全局队列

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

       // 往并行队列中添加下载图片的任务

    dispatch_async(queue, ^{

        

        

        NSLog(@"1111 : curThread = %@", [NSThread currentThread]);

        

        NSURL *url = [NSURL URLWithString:@"http://h.hiphotos.baidu.com/image/pic/item/35a85edf8db1cb13966db40fde54564e92584ba2.jpg"];

        

        NSData *data = [NSData dataWithContentsOfURL:url];

        

        UIImage *image = [UIImage imageWithData:data];

        

        

        // 要求用GCD的方式,在主线程中设置要显示的图片。

        // 好处: 在主线程中,可以直接使用子线程中的资源。使用起来方便,直观。

        //操作ui在主线程中执行

        dispatch_async(dispatch_get_main_queue(), ^{

            _view.image = image;

        });

        

        

    });

    

    

    

    

}



- (void)test11

{

    //    dispatch_queue_t queue = dispatch_get_global_queue(<#long identifier#>, <#unsigned long flags#>)

    dispatch_queue_t queue = dispatch_queue_create("Concurrent Queue", DISPATCH_QUEUE_CONCURRENT);

    

    dispatch_async(queue, ^{

        

        // 做耗时操作

        

        dispatch_async(dispatch_get_main_queue(), ^{

            //操作UI界面

        });

    });

}

@end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值