2014-04-26 114 views
0

我面臨的一些問題,試圖編寫一個相冊:內存問題

一切都很好,但是當我在細胞中插入我的圖片,我總是得到「收到內存警告」或「應用由於內存壓力完成「錯誤。

我嘗試了很多東西,然後再發布但是毫無效果......

請幫我:)這裏是我的代碼:

viewDidLoad中:

self.photosDictionary = [[NSDictionary alloc]initWithObjectsAndKeys:@"1.jpeg",@0,@"2.jpeg",@1, @"3.jpeg",@2,@"4.jpeg",@3,@"5.jpeg", 
         @4,@"6.jpeg",@5,@"7.jpeg",@6,@"8.jpeg",@7,@"9.jpeg",@8, 
         @"10.jpeg",@9,@"11.jpeg",@10,@"12.jpeg",@11,@"13.jpeg", 
         @12,@"14.jpeg",@13,@"15.jpeg",@14,@"16.jpeg",@15,@"17.jpeg", 
         @16,@"18.jpeg",@17, @"19.jpeg",@18,@"20.jpeg",@19,nil]; 

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

if(cell.backgroundView == nil){ 
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[self.photosDictionary objectForKey:@(indexPath.row)]]]; 
} 

} 

回答

1

有多大這些圖像?我在最近的一個應用程序中遇到類似問題。我的第一個建議是加載更小的這些照片的縮略圖版本。這是我們做這件事的方法:

- (UIImage*)imageScaled:(UIImage *) image toMaxSideSize:(int) maxSize 
{ 
    float scaleFactor = 0; 

    if(image.size.width > image.size.height)scaleFactor = maxSize/image.size.width; 
    else scaleFactor = maxSize/image.size.height; 

    CGSize newSize = CGSizeMake(image.size.width * scaleFactor, image.size.height * scaleFactor); 

    UIGraphicsBeginImageContext(newSize); 
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; 
    UIImage* updatedImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return updatedImage; 
} 

所以不是加載完整圖像到每個UITableViewCell中,我們加載這樣的縮略圖。在cellForRowAtIndexPath中:

UIImage * thumbnail = [self imageScaled:[UIImage imageNamed:[self.photosDictionary objectForKey:@(indexPath.row)]] toMaxSideSize:200];

This StackOverflow post涵蓋了一些其他選項,用於重新縮放。 cell.backgroundView.image = thumbnail;

+0

你好,這是更好,因爲我的ipad air不會崩潰,但仍然得到內存警告,它仍然非常緩慢的scull!我不明白! – user3439023

+0

嘗試在後臺線程上調整大小。 – eckyzero