gpt4 book ai didi

memory-management - 大图像的 UICollectionView 的内存未释放

转载 作者:行者123 更新时间:2023-12-02 03:55:17 25 4
gpt4 key购买 nike

我有一个包含 15 个元素的 NSMutableArray,全部都是字符串。这些字符串引用本地存储在应用程序中的图像名称(每个图像大约为 640x640)。我正在 UICollectionView 中显示图像数组。

当我重新加载 collectionView 来显示图像时,我的内存使用量猛增,正如您期望显示大 png 一样(尽管它的占用空间比我预期的要大得多)。

真正的问题是这些图像使用的内存永远不会被释放。因此,尽管我从数组中删除了所有对象,删除了 collectionView 并将所有内容设置为 nil,但没有释放任何内存。

这是为什么呢?如果我删除这些对象并删除 ViewController,我希望我的内存能够恢复到原来的水平。

更新:代码片段

ViewController.m

@implementation ViewController

static NSString *CellIdentifier = @"photoCell";

-(void)viewDidLoad{

[super viewDidLoad];

self.photoCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, 320) collectionViewLayout:self.photoSpringFlowLayout];
[self.photoCollectionView setDataSource:self];
[self.photoCollectionView setDelegate:self];
[self.view addSubview:self.photoCollectionView];
[self.photoCollectionView registerClass:[PhotoPreviewCell class] forCellWithReuseIdentifier:CellIdentifier];

self.imagesAray = [[NSMutableArray alloc] initWithObjects:@"photo1", @"photo2", @"photo3", @"photo4", @"photo5", @"photo6", @"photo7", @"photo8", @"photo9", @"photo10", @"photo11", @"photo12", @"photo13", @"photo14", @"photo15", nil];

[self.photoCollectionView reloadData];
}


#pragma mark - UICollectionView Methods

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}

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

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

PhotoPreviewCell *cell = (PhotoPreviewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];

NSString *imageName = self.imagesArray[indexPath.row];
[cell.photoImage setImage:[UIImage imageNamed:imageName]];

return cell;

}

PhotoPreviewCell.m

@implementation PhotoPreviewCell

-(id)initWithFrame:(CGRect)frame{

self = [super initWithFrame:frame];

if(self){

self.photoImage = [[UIImageView alloc] init];
self.photoImage.frame = CGRectMake(0, 0, 160, 160);
self.photoImage.contentMode = UIViewContentModeScaleAspectFit;
[self.contentView addSubview:self.photoImage];

}

return self;
}

最佳答案

好的,原因是从闪存加载图像需要一些时间,并且操作系统试图避免不断加载它,因此它会缓存加载的图像。仅当您使用 imageNamed: 方法时才会缓存它们。如果您在模拟器上进行测试,请释放所有对象并尝试模拟内存警告。这应该会强制操作系统从缓存中删除未使用的图像。

关于memory-management - 大图像的 UICollectionView 的内存未释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24891450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com