簡體   English   中英

iOS:使用UIImage在collectionview reoloaddata中崩潰

[英]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個圖像之后有一個內存警告...有沒有辦法(作為一個線程)沒有內存警告?

不要將圖像存儲到數組,這不是一個好習慣。 隨着圖像數量或圖像大小的增加,它會引發內存警告和崩潰。

備擇方案:

  1. 將圖像名稱存儲在數組中
  2. 將文件路徑存儲在數組中
  3. 將圖像URL存儲在數組中,並使用Async方法將圖像加載到UITableViewUICollectionView

除了調整圖像大小之外,當單元格滾出視圖時,您可以將圖像清零 - 只需實現:

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath 

另外,維護不會淹沒系統的緩存的技巧就像Midhun在評論中建議的那樣 - 使用imageWithContentsOfFile 然后創建一個NSCache,並使用圖像名稱或其他一些識別密鑰將圖像填入其中。 當您需要圖像時,如果它在緩存中,請將其拉​​出。 如果沒有,您可以再次從文件系統中讀取它。 如果需要更多內存,iOS將清除NSCache。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM