iosGCD線程中的通訊

來源:互聯網
上載者:User

標籤:線程   ios   ios開發   多線程   url   

今天讓我們來看一看ios線程中是怎麼樣通訊的。

#import "ViewController.h"


@interface ViewController ()

{

    UIImageView *_image;

}

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];


    

    CGRect frame = [[UIScreen mainScreen]bounds];

    

    _image = [[UIImageViewalloc]init];

    _image.frame =CGRectMake(0,0, frame.size.width,frame.size.height-300);

    

    [self.viewaddSubview:_image];

    

}

//當使用者觸控螢幕幕的時候,開啟一個線程,下載圖片

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

{

        [selfperformSelectorInBackground:@selector(downloadImage)withObject:nil];

}

//子線程的任務,負責下載網路中的圖片資源

-(void)downloadImage

{

    // 1. 構造圖片資源的url

    NSURL *url = [NSURLURLWithString:@"http://c.hiphotos.baidu.com/image/pic/item/e61190ef76c6a7ef2469025dfefaaf51f3de667a.jpg"];

    //2.下載圖片

    NSData *data = [NSDatadataWithContentsOfURL:url];

    //3.將二進位data轉換成圖片對象

    UIImage *image = [UIImageimageWithData:data];

    

    //在ios開發中,更新UI的操作必須放倒主線程中執行

    [_imageperformSelectorOnMainThread:@selector(setImage:)withObject:image waitUntilDone:NO];

       

}


//把下載到的圖片給UIImageView

-(void)setImage:(UIImage *)image

{    _image.image = image;

}

@end




這就是線程中的通訊的方式,當使用者觸摸這個螢幕的時候,就開啟一個線程去執行下載任務,下載完成,取到主線程把下載好的圖片給UIImageView.

iosGCD線程中的通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.