OGeek|极客世界-中国程序员成长平台

标题: ios - CAKeyframeAnimation - 对图像数组进行动画处理会在完成后创建一个巨大的分配 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 10:02
标题: ios - CAKeyframeAnimation - 对图像数组进行动画处理会在完成后创建一个巨大的分配

我正在尝试使用 CAKeyframeAnimationUIImage 数组设置动画。理论上很简单。
文章底部的示例代码。

我的问题是动画完成后,我有一个无法摆脱的巨大泄漏。

初始化代码CAKeyframeAnimation:

- (void)animateImages
{
    CAKeyframeAnimation *keyframeAnimation = [CAKeyframeAnimation animationWithKeyPath"contents"];
    keyframeAnimation.values = self.imagesArray;  // array with images

    keyframeAnimation.repeatCount = 1.0f;
    keyframeAnimation.duration = 5.0;

    keyframeAnimation.removedOnCompletion = YES;

    CALayer *layer = self.animationImageView.layer;

    [layer addAnimation:keyframeAnimation
             forKey"flingAnimation"];
}

在动画中添加代理和手动移除动画会导致相同的泄漏效果:

... // Code to change

keyframeAnimation.delegate = self;

//    keyframeAnimation.removedOnCompletion = YES;
keyframeAnimation.removedOnCompletion = NO;
keyframeAnimation.fillMode = kCAFillModeForwards;

....

然后:

- (void)animationDidStopCAAnimation *)anim finishedBOOL)flag
{
    if (flag)
    {
        [self.animationImageView.layer removeAllAnimations];
        [self.animationImageView.layer removeAnimationForKey"flingAnimation"]; // just in case
    }
}

结果总是一个巨大的分配。内存堆栈的大小与图像的大小成正比:

enter image description here

I uploaded an example to GitHub to check the code.



Best Answer-推荐答案


已解决

我发现了问题。

作为 gabbler是说没有泄漏问题。问题是图像的高分配。

我正在释放包含图像的数组,但是图像并没有从内存中消失。

所以我终于找到了问题:

    [UIImage imageNamed""];

从方法定义:

此方法在系统缓存中查找具有指定名称的图像对象,如果该对象存在,则返回该对象。如果匹配的图像对象尚未在缓存中,则此方法从磁盘或 Assets 分类日志中定位并加载图像数据,然后返回结果对象。你不能假设这个方法是线程安全的。

因此,imageNamed: 将图像存储在私有(private)缓存中。
- 第一个问题是你无法控制缓存大小。
- 第二个问题是缓存没有及时清理,如果你使用 imageNamed: 分配大量图像,你的应用程序可能会崩溃。

解决方案:

直接从Bundle分配图片:

NSString *imageName = [NSString stringWithFormat"imageName.png"];
NSString *path = [[NSBundle mainBundle] pathForResource:imageName

// Allocating images with imageWithContentsOfFile makes images to do not cache.
UIImage *image = [UIImage imageWithContentsOfFile:path];

小问题:

Images.xcassets 中的图像永远不会被分配。因此,将图像移到 Images.xcassets 之外,直接从 Bundle 中分配。

Example project with solution here.

关于ios - CAKeyframeAnimation - 对图像数组进行动画处理会在完成后创建一个巨大的分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27904494/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4