objective - C:从URL加载图片?

Kha*_*lid 2 iphone objective-c uitableview uiimageview

对不起,问题标题.我找不到合适的头衔.

UITableView打开UITableView视图时没有显示来自网址的内容图像,直到图像加载并且需要时间.

我通过php从JSON获取图像.

我想显示表格然后图像加载过程.

这是我的应用程序的代码:

NSDictionary *info = [json objectAtIndex:indexPath.row];
cell.lbl.text = [info objectForKey:@"title"];
NSString *imageUrl = [info objectForKey:@"image"];
cell.img.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]]];
[cell.img.layer setBorderColor: [[UIColor blackColor] CGColor]];
[cell.img.layer setBorderWidth: 1.0];

return cell;
Run Code Online (Sandbox Code Playgroud)

抱歉,我的英语很弱.

Joe*_*tti 7

在单独的线程上执行Web请求,以便不阻止UI.这是一个使用的例子NSOperation.请记住只更新主线程上的UI,如图所示performSelectorOnMainThread:.

- (void)loadImage:(NSURL *)imageURL
{
    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                        initWithTarget:self
                                        selector:@selector(requestRemoteImage:)
                                        object:imageURL];
    [queue addOperation:operation];
}

- (void)requestRemoteImage:(NSURL *)imageURL
{
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
    UIImage *image = [[UIImage alloc] initWithData:imageData];

    [self performSelectorOnMainThread:@selector(placeImageInUI:) withObject:image waitUntilDone:YES];
}

- (void)placeImageInUI:(UIImage *)image
{
    [_image setImage:image];
}
Run Code Online (Sandbox Code Playgroud)