Advanced iOS when loading large amounts of local memory soar pictures

Encountered this problem today, app Lane took over 100 pictures, each picture is probably about the size of 200KB, when entering CollectionView performed Photo Gallery, memory soared, will flash back to slide up and down.

The Internet to find many programs failed to resolve, finally saw an article only after solve this problem.

Here are some of their own solutions:

Scene: I used here is UICollectionView to show, his show four pictures, probably sixty-seven line.

- (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;
}

Use a variable to store the data in a cell, if the data is present, you do not need to load again. When loading a picture, the picture compression (can be modified according to their needs).

#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

This perfect solution to soaring leads app flash memory back, as to the use to which the resizeScaleImage: method, you can go and see " iOS picture memory optimization " of this article.

 

Guess you like

Origin www.cnblogs.com/sjxjjx/p/11772396.html