• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - CAKeyframeAnimation - 对图像数组进行动画处理会在完成后创建一个巨大的分配

[复制链接]
菜鸟教程小白 发表于 2022-12-13 10:02:24 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在尝试使用 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap