Question

i am facing some problems trying to code a photo gallery :

Everything is fine but when I insert my images in the cells, i always get the "received memory warning" or "app finished due to memory pressure" error.

I tried a lot of things before posting but nothing worked...

Please help me :) Here is my code :

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)]]]; 
}

}
Was it helpful?

Solution

How big are these images? I had a similar issue in a recent app. My first suggestion would be to load thumbnail versions of these photos that are much smaller. Here's our method for doing it:

- (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;
}

So instead of loading the full image into each UITableViewCell, we load the thumbnail like this. in cellForRowAtIndexPath:

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

This StackOverflow post covers some other options for rescaling. cell.backgroundView.image = thumbnail;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top