3

我有一個15個元素的NSMutableArray,他們都是字符串。這些字符串指的是存儲在本地應用程序中的圖像名稱(每個圖像大約爲640x640)。我在UICollectionView中顯示圖像數組。內存不被釋放的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; 
} 
+0

請張貼一些代碼,你如何加載圖像。 – blazejmar

+0

就我個人而言,我會明確處理清晰程序中的圖像。 –

+0

添加了一些代碼,希望更好地解釋場景。你指的是什麼明確的例程,託尼? –

回答

2

好了,所以這樣做的原因是,從flash加載圖像需要一定的時間和OS嘗試爲了避免加載它,所以它緩存加載的圖像。只有當您使用imageNamed:方法時纔會緩存它們。如果您正在模擬器上測試釋放所有對象並嘗試模擬內存警告。這應該強制操作系統從緩存中刪除未使用的圖像。

+0

是的,你是對的,imageNamed:是問題的原因。 imageNamed:緩存我的圖像,並失去對內存的控制(不像imageWithContentsOfFile:它不緩存圖像)。因此,知道操作系統將在需要時清空緩存(即當應用程序收到低內存警告時),我不應該擔心看到我的內存足跡增加 - 因爲當我收到內存警告時操作系統將清空緩存。這是一個正確的假設嗎? –

+0

只要你的內存佔用不夠大,加載所有這些圖像,你應該沒問題。如果您將它們包含在捆綁包中,請儘量保持它們的大小以便在不升級的情況下進行顯示,這樣可以減少二進制大小和內存佔用量。 – blazejmar