大图集合视图的内存未被释放

3
我有一个包含15个元素的NSMutableArray,所有元素都是字符串。这些字符串指向本地存储在应用程序中的图像名称(大约每个图像的大小为640x640)。我正在UICollectionView中显示这些图像数组。
当我重新加载collectionView以显示这些图像时,我的内存使用量会急剧上升,因为显示大型png图像(尽管其占用空间比我预期的要大得多)。
真正的问题在于,这些图像所使用的内存永远不会被释放。因此,即使我从数组中删除了所有对象,删除了collectionView并将所有内容设置为空,也没有释放任何内存。
为什么会这样?如果我删除这些对象并删除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;
}

请发布一些代码,展示如何加载图像。 - blazejmar
个人而言,我会在清除例程中显式地处理图像。 - Tony Hopkinson
添加了一些代码,希望更好地解释情境。你所提到的清除例程是什么,托尼? - Andrew Davis
1个回答

2

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


1
是的,你说得对,imageNamed: 是问题的原因。imageNamed: 会缓存我的图片,我失去了对内存的控制(不像 imageWithContentsOfFile: 不会缓存图片)。所以,知道操作系统在需要时会清空缓存(即当应用程序收到低内存警告时),我不应该担心看到我的内存占用增加 - 因为当我收到内存警告时,操作系统会清空缓存。这个假设正确吗? - Andrew Davis
只要加载所有这些图像时,您的内存占用不够大,那么就应该没问题。如果将它们包含在捆绑包中,请尽量保持它们足够小,以便在不需要缩放的情况下显示,这将减少二进制大小和内存占用。 - blazejmar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接