ios中子线程如何加载图片

来源:互联网 发布:自动顶贴软件 编辑:程序博客网 时间:2024/06/05 10:05

方法一:

GCD

//在主线程里调用,然后跳到一个子线程。

dispatch_async(dispatch_get_global_queue(0,0), ^{

//IMAGE_URL为定位的宏。为图片的地址

//在子线程里完成对网上图片的解析

        NSURL *imageURL = [NSURL URLWithString:IMAGE_URL];

        NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

        //完成解析后然后跳到主线程里执行UIImageView的操作。

       dispatch_async(dispatch_get_main_queue(), ^{

//创建一个UIImageView

            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0, 320, 460)];

 //对UIImageView加载下载好的图片。

            imageView.image = [UIImageimageWithData:imageData];

            [self.windowaddSubview:imageView];

            [imageViewrelease];        

        });

    });

方法二:
新建一个子线程

 NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(sonThreah) object:nil];

启动子线程    

[thread start];

//实现子线程里的方法

-(void)sonThreah{   

//跳到子线程,对图片进行解析

    NSURL *imageURL = [NSURL URLWithString:IMAGE_URL];

    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

//解析完跳到主线程

    [selfperformSelectorOnMainThread:@selector(showImage:)withObject:imageData waitUntilDone:NO];


}

-(void)showImage:(NSData *)data {

 //主线程完成对图片的加载

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0, 320, 460)];

    [self.windowaddSubview:imageView];

    imageView.image = [UIImageimageWithData:data];

    [imageView release];   

}


原创粉丝点击