zoukankan      html  css  js  c++  java
  • 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图片内存优化》这篇文章。

  • 相关阅读:
    CentOS7安装MySQL5.7
    .gdbinit文件配置
    Linux 动态库加载
    GDB常用调试命令(二)
    git删除缓存区中文件
    git添加空文件夹
    Linux 打开core dump功能
    C++ 预处理器
    C++ 模板
    C++ 命名空间
  • 原文地址:https://www.cnblogs.com/sjxjjx/p/11772396.html
Copyright © 2011-2022 走看看