iosGCD基礎用法

來源:互聯網
上載者:User

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


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.