UITableviewCell 在块内返回为 nil [英] UITableviewCell returning as nil inside block

查看:25
本文介绍了UITableviewCell 在块内返回为 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对tableView:cellForRowAtIndexPath:的实现如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    BSProductCell *cell = [tableView dequeueReusableCellWithIdentifier:BSProductCellIdentifier];

    cell.productImageView.image = [UIImage imageNamed:@"Placeholder"];

[[BSImageLoader sharedInstance] getImageWithURL:self.dataSourceArray[indexPath.row] withCompletionBlock:^(UIImage *image, BOOL fromCache, NSString *error){
    BSProductCell *tableCell = (BSProductCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    [tableCell.productImageView setImage:image];
    NSLog(@"%@", tableCell);
}];
    return cell;

}

getImageWithURL:withCompletionBlock: 如果在本地缓存中找不到图像,则从指定的 URL 下载图像,或者仅从缓存中返回图像.起初,当视图加载并且单元格被填充时,所有事情都按预期进行:图像正在被下载,然后被放置在单元格中.问题是当我开始滚动 tableview 时,NSLog 显示 (null).我就是不明白为什么 tableCell 对象为空.

The getImageWithURL:withCompletionBlock: either downloads the image from the specified URL if it cannot find it within the local cache or just returns it from the cache. At first, when the view loads and the cells get populated all the things go as expected: the images are being downloaded and then placed within the cells. The problem is when I start scrolling the tableview, the NSLog shows (null). I just cannot figure out why the tableCell object is null.

PS:我在遵循几乎相同的来自 Apple 的示例.我还检查了 self.tableViewindexPath 在块内都不是 nil.

PS: I wrote my example after following an almost identical example from Apple. Also I checked and neither self.tableView nor indexPath are not nil inside the block.

推荐答案

块是异步的,你应该在块外创建你的单元格,只在里面设置图像:

The block is asynchronous, you should create your cell outside the block and only set the image inside :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    BSProductCell *cell = [tableView dequeueReusableCellWithIdentifier:BSProductCellIdentifier];
    if(cell==nil){
        cell = [[BSProductCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:BSProductCellIdentifier];
    }

    cell.productImageView.image = [UIImage imageNamed:@"Placeholder"];

    [[BSImageLoader sharedInstance] getImageWithURL:self.dataSourceArray[indexPath.row] withCompletionBlock:^(UIImage *image, BOOL fromCache, NSString *error){

        //Here you check that the cell is still displayed
        if([tableView cellForRowAtIndexPath:indexPath]){
            [cell.productImageView setImage:image];
            NSLog(@"%@", cell);
        }
    }];
    return cell;
}

这篇关于UITableviewCell 在块内返回为 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆