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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章