【发布时间】:2019-09-11 09:32:01
【问题描述】:
我的应用需要在 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 加载时,内存会快速增加,并且似乎所有图像都已加载到内存中。
有什么好的想法来解决这个问题吗?我只是想节省内存。
顺便说一句,有谁知道实现这种需求的常用方法是什么?我认为将所有图像加载到内存是最愚蠢的方式......我最初的tableview行代码如下:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (!_isLoading) {
return self.dataArray.count; // about 2000... That's terrible
} else {
return 0;
}
}
谢谢!
【问题讨论】:
-
您的图片是来自本地还是 WebAPI?
-
如果你想从服务器加载图像,请使用github.com/SDWebImage/SDWebImage
-
我的图片来自本地。
-
您遇到的问题来自图像缓存。每个图像都被缓存,它增加了使用的内存。我认为您可以尝试创建不同的图像缓存并清理远离表视图当前索引的缓存。
-
@m1sh0 感谢您的建议。当 tableview 没有出现在屏幕上时,一切正常。 dataArray 包含图像的路径,而不是图像本身。
标签: ios image uitableview