iOS进阶之加载大量本地图片时内存飙升

时间:2019-10-31
本文章向大家介绍iOS进阶之加载大量本地图片时内存飙升,主要包括iOS进阶之加载大量本地图片时内存飙升使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

今天遇到了这个问题,app里拍了100多张图片,每张图片大概200KB左右的大小,当进入CollectionView进行图片展示时,内存出现飙升,上下滑动时会闪退。

在网上找了许多方案都没能解决,最后看到一篇文章后,才解决了这个问题。

下面介绍一下自己的解决办法:

场景:我这里使用的是UICollectionView来进行展示,一行显示4张图片,大概六七行。

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.photoList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 每一张图片都是唯一的Cell
    NSString *cellID = [NSString stringWithFormat:@"%@_%zd", TestCellID, indexPath.item];
    [collectionView registerNib:[UINib nibWithNibName:@"TestCell" bundle:nil] forCellWithReuseIdentifier:cellID];
    
    TestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    cell.model = self.photoList[indexPath.item];
    return cell;
}

在cell中使用一个变量来保存数据,如果存在数据,则不需要再次加载。在加载图片的时候,对图片进行压缩(可根据自己的需求进行修改)。

#import "TestCell.h"
#import "TestModel.h"

@interface TestCell ()

@property (weak, nonatomic) IBOutlet UIImageView *photoImage;
/** 保存模型 */
@property(nonatomic, strong) TestModel *saveModel;

@end

@implementation TestCell

- (void)setModel:(TestModel *)model {
    _model = model;
    
    if (self.saveModel.ID.length > 0) {
        return;
    } else {
        self.saveModel = model;
    }

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSData *data = [[NSData alloc] initWithContentsOfFile:model.path];
        UIImage *tempImage = [UIImage imageWithData:data];
        // 这步操作比较耗时
        image = [tempImage resizeScaleImage:0.1];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.photoImage.image = image;
        });
    }
}

- (TestModel *)saveModel {
    if (!_saveModel) {
        _saveModel = [[TestModel alloc] init];
    }
    return _saveModel;
}

@end

这样就完美解决了内存飙升导致app闪退了,至于里面使用到的 resizeScaleImage: 方法,可以去看看《iOS图片内存优化》这篇文章。

原文地址:https://www.cnblogs.com/sjxjjx/p/11772396.html