本例中项目大致流程是先由客户端拍照或者选择图库中的图片进行上传,然后可以从详情页面中浏览所有上传的图片,由于图片是按照相册进行分类,而每个相册中最多可以有50张照片,极限的情况是详情页面最多可以有20多个相册,由此导致需要对图片的加载进行必要的优化,避免程序占用内存过多导致程序崩溃
优化思路如下:
1、限制图片缓存占用的最大内存数
设置SDWebImage中imageCache的setMaxMemoryCountLimit
[[SDWebImageManager sharedManager].imageCache setMaxMemoryCountLimit:15];
//imageCache为SDWebImageManager中的独立缓存单元
2、控制器视图滑动开始时对图片处理线程的监管,以及对图片缓存所占用的内存的清理
在加载图片的控制器中,当页面开始滑动时暂停SDWebImage中所有任务的执行(取消掉当前所有的下载图片的operation),并且清除内存中的图片缓存,再将滑动状态结束的标志位置为No,此标志位用于加载图片时的相关操作,即第4步操作
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
self.isEndDecelerating = NO;
NSLog(@"scrollViewWillBeginDragging-----");
[SDWebImageManager.sharedManager cancelAll];
[SDWebImageManager.sharedManager.imageCache clearMemory];
}
3、控制器视图滑动结束时对相册的操作
控制器滑动结束时,将代表滑动结束的标志位置为YES,并将视图可见范围内的相册重新加载图片
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
self.isEndDecelerating = YES;
NSLog(@"scrollViewDidEndDecelerating-----");
NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
for (NSIndexPath *indexPath in visiblePaths) {
switch (indexPath.row) {
case 21:
{
HeadPhotoCell * cell = (HeadPhotoCell *)[self.tableView cellForRowAtIndexPath:indexPath];
[cell.album reloadData];
}
break;
...
...
default:
...
break;
}
}
}
4、加载图片时的管理
加载图片时,根据控制器视图的滑动状态选择展示缩略图还是清除image,减小程序运行压力
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CDCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CDCollectionCell" forIndexPath:indexPath];
NSString * imgUrl = [self.totalArray objectAtIndex:indexPath.section][indexPath.row];
NSString * urlStr = [NSString stringWithFormat:@"%@/%@?width=30&height=30",ImageServerUrl,imgUrl];
if(self.parentViewCtrl.isEndDecelerating) {
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:urlStr]];
}else{
cell.imageView.image = nil;
}
return cell;
}
描述或解决不当之处,欢迎大家批评指正