ios - 当我向下滚动很多时,带有图像的 UITableView 使应用程序崩溃

标签 ios uitableview crash uiimageview afnetworking

我有这个简单的 UITableView,每个单元格都有一个与之对应的图像。我所做的只是在每个单元格中显示图像的标题和图像本身。这是我的 cellForRowAtIndexPath:

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

    // this is where the data for each cell is
    NSDictionary *dataForThisCell = cachedData.posts[indexPath.row][@"data"];

    // this creates a new cell or grabs a recycled one, I put NSLogs in the if statement to make sure they are being recycled, they are.
    post *cell = (post *) [self.tableView dequeueReusableCellWithIdentifier:@"postWithImage"];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"postWithImage" owner:self options:nil]objectAtIndex:0];
        [cell styleCell];
    }

    // if this cell has an image we need to stick it in the cell
    NSString *lowerCaseURL = [dataForThisCell[@"url"] lowercaseString];
    if([lowerCaseURL hasSuffix: @"gif"] || [lowerCaseURL hasSuffix: @"bmp"] || [lowerCaseURL hasSuffix: @"jpg"] || [lowerCaseURL hasSuffix: @"png"] || [lowerCaseURL hasSuffix: @"jpeg"]) {

        // if this cell doesnt have an UIImageView, add one to it. Cells are recycled so this only runs several times
        if(cell.preview == nil) {
            cell.preview = [[UIImageView alloc] init];
            [cell.contentView addSubview: cell.preview];
        }

        // self.images is an NSMutableDictionary that stores the width and height of images corresponding to cells.
        // if we dont know the width and height for this cell's image yet then we need to know now to store it
        // once the image downloads, and then cause our table to reload so that heightForRowAtIndexPath
        // resizes this cell correctly
        Boolean shouldReloadData = self.images[dataForThisCell[@"name"]] == nil ? YES : NO;

        // download image
        [cell.preview cancelImageRequestOperation];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: dataForThisCell[@"url"]]];
        [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
        [cell.preview setImageWithURLRequest: request
                              placeholderImage: [UIImage imageNamed:@"thumbnailLoading.png"]
                                       success: ^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

                                           // if we indicated earlier that we didnt know the dimensions of this image until
                                           // just now after its been downloaded, then store the image dimensions in self.images
                                           // and tell the table to reload so that heightForRowAtIndexPath
                                           // resizes this cell correctly
                                           if(shouldReloadData) {
                                               NSInteger imageWidth = image.size.width;
                                               NSInteger imageHeight = image.size.height;
                                               if(imageWidth > [ColumnController columnWidth]) {
                                                   float ratio = [ColumnController columnWidth] / imageWidth;
                                                   imageWidth = ratio * imageWidth;
                                                   imageHeight = ratio* imageHeight;
                                               }
                                               if(imageHeight > 1024) {
                                                   float ratio = 1024 / imageHeight;
                                                   imageHeight = ratio * imageHeight;
                                                   imageWidth = ratio* imageWidth;
                                               }
                                               self.images[dataForThisCell[@"name"]] = @{ @"width": @(imageWidth), @"height": @(imageHeight), @"titleHeight": @([post heightOfGivenText: dataForThisCell[@"title"]]) };
                                               [self.tableView reloadData];

                                           // otherwise we alreaady knew the dimensions of this image so we can assume
                                           // that heightForRowAtIndexPath has already calculated the correct height
                                           // for this cell
                                           }else{

                                               // assign the image we downloaded to the UIImageView within the cell
                                               cell.preview.image = image;

                                               // position the image
                                               NSInteger width = [self.images[dataForThisCell[@"name"]][@"width"] integerValue];
                                               NSInteger height = [self.images[dataForThisCell[@"name"]][@"height"] integerValue];
                                               cell.preview.frame = CGRectMake( ([ColumnController columnWidth] - width)/2 , [self.images[dataForThisCell[@"name"]][@"titleHeight"] integerValue] + 10, width, height);

                                           }

                                       }
                                       failure: ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {}];


    }

    // set title of the cell
    cell.title.text = [NSString stringWithFormat: @"%@\n\n\n\n\n", dataForThisCell[@"title"]];

    `enter code here`// ask for a restyle
    [cell setNeedsLayout];

    // returns my customized cell
    return cell;

}

发生的事情是一切都按照我想要的方式运行,但是当我向下滚动大约 100 个单元格时,我的应用程序的背景变黑了几秒钟,然后我看到了我的主屏幕(我已经看到了一些人们称之为 HSOD - 死亡主屏幕)。有时在 xcode 的控制台中,我会在崩溃前看到内存警告,有时却看不到。

我知道无论问题是什么,都与将图像放入单元格有关。如果我只注释掉这一行:

cell.preview.image = image;

然后一切正常,不再崩溃(但当然图像不会显示在单元格中)。

单元格正在被重用,我知道这是有效的,为了更好的衡量,我将 UIImageView 的图像属性设置为 nil:

- (void) prepareForReuse {
    [super prepareForReuse];
    if(self.preview != nil)
        self.preview.image = nil;
}

在我的 appDelegate 中我也定义了这个:

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {

    [UIImageView clearAFImageCache];

}

这会删除图像缓存,但这也不能解决问题(无论如何,iOS 应该会在出现内存警告时自动清除图像缓存)。

我对我的项目进行了分析,它报告没有内存泄漏,这是分析器显示的,以及崩溃时的分配情况:

enter image description here

除了大约 2/3 的应用程序崩溃时间在控制台中偶尔出现内存警告外,控制台中没有出现其他错误,我也没有遇到任何断点或异常。

最佳答案

所有这些分配都是在每次请求时创建新的表格 View 单元格,而不是重复使用现有的单元格。如果不为从 UINib 创建的单元格设置 reuseIdentifierdequeueReusableCellWithIdentifier: 将始终返回 `nil。

要解决此问题,请添加以下代码(引用 in this question):

[self.tableView registerNib:[UINib nibWithNibName:@"nibname" 捆绑:无] forCellReuseIdentifier:@"cellIdentifier"];

关于ios - 当我向下滚动很多时,带有图像的 UITableView 使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16699342/

相关文章:

ios - 自动布局 - 按百分比定位

swift - Tableview : Name is selected, 将 ID(而不是名称)存储在变量中的最佳方法?

ios - 从iPhone删除应用程序时Xcode崩溃

iphone - iPhone配置实用程序3.3无法安装配置

ios - 在 iOS 6 中保留应用程序

ios - 如何使用单选按钮隐藏表格 View 中的部分?

ios - Swift tableview 在编辑一个单元格时更改随机单元格的值

opengl - LWJGL - glEnableVertexAttribArray(1) 后游戏崩溃

jquery - 网站崩溃(在)Firefox

ios - 如何激活具有预设期限的 UISearchDisplayController?