如何在块内分配UIimage

时间:2013-06-28 21:00:54

标签: ios url asynchronous uiimageview

我正在向URL请求下载图片。我将其作为NSData对象收到,但当我尝试将其转换为UIimage with imageWithData:时,UIImage未加载。这是我的代码

__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
__weak typeof(request)weakRequest = request;
__block UIImage * imager;
__block NSData * image;
[request setCompletionBlock:^{
    [self parseXMLFileAtFileId:[weakRequest responseData]];
    if (!files){
        cell.correctImage.image = [UIImage imageNamed:@"sidebarPlaceholder"];
    }
    else{

        NSURL *url = [NSURL URLWithString:[self downloading:[files objectAtIndex:0]]];
        __block ASIHTTPRequest *requester = [ASIHTTPRequest requestWithURL:url];

        __weak typeof(request)weakRequesting = requester;
        [requester setCompletionBlock:^{
            image =  [weakRequesting responseData];
            imager = [UIImage imageWithData:image];
            cell.correctImage.image = imager;
            [cell layoutIfNeeded];
        }];

        [requester startAsynchronous];
    }
}];

之前我通过明确说明UIImageView的大小来实现它,但UITableviewCell应该由它来处理。如何让图像显示出来?

1 个答案:

答案 0 :(得分:1)

尝试在主线程中运行这些代码块,因为看起来您正在尝试设置图像并在后台线程中更新布局。

之后立即使用以下NSThread方法
UIImage *imager = [UIImage imageWithData:image]

[self performSelectorOnMainThread:@selector(updateImage:) withObject:imager waitUntilDone:false];

//定义更新图像的方法

- (void)updateImage: (UIImage *)paramImage {
    cell.correctImage.image = paramImage;
    [cell layoutIfNeeded];
}