Dan Hanly
Dan Hanly

Reputation: 7839

Memory Management in Loading Images

I have a panning gesture that pans across a series of images. I'm not sure how to correctly manage the memory for this, after panning for a certain length of time, I'm getting crashes.

animImage is a UIImageView;

Here is how it works:

- (IBAction) panAnim:(UIPanGestureRecognizer *)sender{
    CGPoint translate = [sender translationInView:sliderView];

    if (translate.x >= lastPoint) {
        difference = translate.x - lastPoint;
        [self forwardAnim:difference];
    } else {
        difference = lastPoint - translate.x;
        [self backwardAnim:difference];
    }
    lastPoint = translate.x;
}

-(void)forwardAnim:(CGFloat)speed{
    NSInteger newFrame = currentFrame+speed;
    currentFrame = newFrame;
    if (currentFrame>=totalFrames) {
        currentFrame=0;
    }
    NSString *newImagePath = [NSString stringWithFormat:@"%@", [currentAnimation objectAtIndex:currentFrame]];  
    animImage.image = [UIImage imageNamed:newImagePath];
}

-(void)backwardAnim:(CGFloat)speed{
    NSInteger newFrame = currentFrame-speed;
    currentFrame = newFrame;
    if (currentFrame<0) {
        currentFrame=(totalFrames-1);
    }
    NSString *newImagePath = [NSString stringWithFormat:@"%@", [currentAnimation objectAtIndex:currentFrame]];  
    animImage.image = [UIImage imageNamed:newImagePath];
}

The animation detects position of the translate and calculates what 'frame' the animation should be at and then swaps out the image.

I'm getting a very smooth animation for this but obviously I'm causing a crash because I'm not managing the memory correctly. I'm getting Memory Warnings and then crashes - but only when I've been scrolling through the images for a while.

I need to figure out a way to pre-load 100 images at a time, so I can only keep the memory of 100 images. It's strange because the images are opened and closed properly in the IO Output in Instruments.

Thanks for your help!

Cheers, D

Upvotes: 0

Views: 756

Answers (1)

Caleb
Caleb

Reputation: 124997

+[UIImageView imageNamed:] caches the images it loads, so it's not surprising that your memory usage keeps increasing. You might try changing those +imageNamed: calls to +imageWithContentsOfFile: instead. That may hurt your animation performance, but I suspect you'll see memory usage drop significantly.

A memory warning doesn't mean that a crash is imminent. It'd help if you'd post the details of the crash. Looking at the crash log, you should be able to identify a line in your code that leads to the crash -- it may be a few frames from the top of the stack. Find that line, put a breakpoint a line or two before it, and step through the code imagining what could happen on each line that might cause a problem -- failed allocation, bad value, etc.

BTW, your 25kB image files likely expand to something much larger in memory.

Upvotes: 1

Related Questions