[英]iOS: crash in collectionview reoloaddata with UIImage
在我的应用程序中,我有这个代码:
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return images.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"gallerycell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *backImageCell = (UIImageView*)[cell viewWithTag:100];
[backImageCell setImage:[images objectAtIndex:indexPath.item]];
if([indexPath row] == ((NSIndexPath*)[[collectionView indexPathsForVisibleItems] lastObject]).row){
[activity_view stopAnimating];
[UIView animateWithDuration:0.8 animations:^{
back.alpha = 0;
}];
}
return cell;
}
数组图像包含200x150大小的UIImage,它们的kb大小约为42kb,是UIImage的正常数组。
当我为这个集合视图重新加载数据时,我在15个图像之后有一个内存警告...有没有办法(作为一个线程)没有内存警告?
不要将图像存储到数组,这不是一个好习惯。 随着图像数量或图像大小的增加,它会引发内存警告和崩溃。
备择方案:
UITableView
或UICollectionView
除了调整图像大小之外,当单元格滚出视图时,您可以将图像清零 - 只需实现:
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
另外,维护不会淹没系统的缓存的技巧就像Midhun在评论中建议的那样 - 使用imageWithContentsOfFile
。 然后创建一个NSCache,并使用图像名称或其他一些识别密钥将图像填入其中。 当您需要图像时,如果它在缓存中,请将其拉出。 如果没有,您可以再次从文件系统中读取它。 如果需要更多内存,iOS将清除NSCache。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.