UIImage Animation Causing App to Crash / Memory Le

2020-02-13 03:57发布

问题:

I'm using a UIImage animation and it is causing numerous memory leaks and crashes for different users using the application.

Below is my code. I am preloading the set of two animation in viewDidAppear

pointsView.image = [UIImage imageNamed:@"C72.png"];

    NSMutableArray *menuanimationImages = [[NSMutableArray alloc] initWithCapacity:21];
    NSString *imageName;

    for( int aniCount = 0; aniCount < 72; aniCount++ )
    {
        imageName = [NSString stringWithFormat:@"C%d.png", aniCount];
        [menuanimationImages addObject:[UIImage imageNamed:imageName]];
    }

    pointsView.animationImages = menuanimationImages;

    pointsView2.image = [UIImage imageNamed:@"I72.png"];

    NSMutableArray *menuanimationImagess = [[NSMutableArray alloc] initWithCapacity:21];
    NSString *imageNames;

    for( int aniCounts = 0; aniCounts < 72; aniCounts++ )
    {
        imageNames = [NSString stringWithFormat:@"I%d.png", aniCounts];
        [menuanimationImagess addObject:[UIImage imageNamed:imageNames]];
    }

    pointsView2.animationImages = menuanimationImagess;
}

I am then running the animation using

pointsView.animationDuration = 3.11;
pointsView.animationRepeatCount = 1;
[pointsView startAnimating];

Any suggestions?

回答1:

Please read my blog post about this subject: video-and-memory-usage-on-ios-devices. The root of the problem is that you simply cannot have this many images loaded into main memory at the same time. You need to simply not use the UIImageView.animationImages API, it is badly broken and lures developers into writing bad code that will crash when run on the device.



回答2:

You are loading it looks like 72 png images into memory at once? And depending on the size of those images, you could probably be reaching the memory limits of some older devices causing them to give a memory warning and eventually crash. My suggestion is to not do a 72 image animation. You could try to compress each image which will lower their quality and memory size but loading 72 images to do an animation is just not good in the first place.