Search code examples
ioscrashgifsdwebimage

Loading a big gif with SDWebImage caused iOS app crash with memory error


I am fetching a full screen image from url returned from internet in my UIImageView on a UIScrollView with SDWebImage framework like this:

[imageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"placeholder"] options:SDWebImageCacheMemoryOnly completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
    if (!error) {
        //added as subview
    } else {
        //show error
    }
}];

When the image was with format of jpg or png, it shows well, even some normal sized gif. But when there was a big gif, it would cause crash and XCode gives such error:

Message from debugger: Terminated due to Memory Error

UPDATE: The gif image that causes crash everytime is 299px*299px and 570KB big. For those who are interested in seeing the gif, the link is:

http://ww4.sinaimg.cn/large/604e48d0jw1evcn03adjjg208b08bdv0.gif

I can recreate this every time I clicked on the preview thumbnail. How can I solve this? What tool to use to observe the root cause? I did some research and I guess if it's caused by the fact that I was using the option: SDWebImageCacheMemoryOnly, and the big gif cost most of my app's memory so it crashed. Thanks.


Solution

  • The thing that I notice about your animated gif image is that it is a very long (in terms of frame count) animation - 3191 frames. Every single one of those frames is 300x300, for a total of almost 300 million pixels. And we must hold all those pixels in memory at once: there's no other way to display the frames at speed. And it seems to be coded as RGB, so every pixel is 4 bytes. If I'm right, that's more than a gigabyte of memory needed to display this thing. That certainly is what Graphic Converter is suggesting:

    enter image description here

    So you're right, I can well imagine that displaying this might be troublesome. My advice would be: don't.