UITableView具有大量图像

时间:2019-04-22 06:38:36

标签: ios image uitableview

我的应用程序需要在UITableView中显示大量图像(约2000张)。基本上,我使用以下代码构造UITableViewCell:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    } 

    // Some Operations...

    NSString *path = [self.dataArray jk_objectWithIndex:indexPath.row];
    UIImage *img = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = img;

    return cell;
}

这可以工作,但是在加载表视图时,内存会快速增加,并且似乎所有图像都已加载到内存中。

有什么好主意可以解决吗?我只想保存内存。

顺便说一句,有人知道实现此需求的通用方法是什么?我认为将所有图像加载到内存是最愚蠢的方式...而我在tableview的初始行中的代码如下:


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (!_isLoading) {
        return self.dataArray.count; // about 2000... That's terrible
    } else {
        return 0;
    }
}

谢谢!

2 个答案:

答案 0 :(得分:1)

您的代码有两个问题。

  • 首先,也是最重要的一点,图像很大,但是表中图像的显示很小。错了您应该仅以实际需要的尺寸加载图像。

  • 第二,默认情况下会缓存图像。您需要防止在加载这些图像时对其进行缓存。

通过使用ImageIO框架,您可以在cellForRowAt中轻松地完成这两项操作。

答案 1 :(得分:0)

我想出了解决这个问题的方法。将这些代码行添加到cellForRowAtIndexPath:

CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
    CGRect rectInSuperview = [tableView convertRect:rectInTableView toView:[tableView superview]];
    if ( rectInSuperview.origin.y > SCREEN_HEIGHT || rectInSuperview.origin.y + rectInSuperview.size.height < 0 ) {
        cell.imageView.image = self.placeholder;
    } else {
        NSString *path = [self.dataArray jk_objectWithIndex:indexPath.row];
        UIImage *img = [UIImage imageWithContentsOfFile:path];
        cell.imageView.image = img;
    }

首先,我检查该单元格是否显示在屏幕上。如果是,则imageView显示我的数据图像。如果不是,则显示占位符。另外,占位符是[UIImage imageNamed:]的init。这是最好的方法,因为它将经常使用。