今天遇到了這個問題,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圖片內存優化》這篇文章。