SKTextureAtlas 留在内存中

SKTextureAtlas staying in memory

我做了一个快速项目来了解 SpriteKit 如何从内存中释放地图集。每次点击屏幕时,都会创建一个图集并将其加载到内存中。对图集的唯一引用是您在下面的代码中看到的内容,我认为因为 var 在非转义函数中,所以它没有强引用。我的目标是最终释放之前加载到内存中的地图集,但是内存堆积并最终崩溃。

我知道图集只应该加载一次,Apple 在这里 (Working with Sprites) 关于为什么不释放纹理的三点

有人能帮我理解为什么会这样吗?

class GameScene: SKScene {

     override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        var atlas:SKTextureAtlas? = SKTextureAtlas(named: "Title")

        atlas?.preload {

            atlas = nil

            print("Loaded")

        }

    }

}

每次检测到触摸时都会创建一个新的内存阶梯

您每次触摸屏幕时都在分配和初始化一个新纹理,这意味着您将不会在函数第二次运行时获得引用,因为它正在被新纹理指针替换

要解决此问题,请在 var 声明之前添加 static,这将防止变量在程序完成之前被新指针覆盖

例如 如果你输入那个函数

var nm = 5 
print(nm)  // will print 5 every time

nm += 1
print(nm)  // will print 6 every time 

nm 每次都被覆盖 在声明之前放置静态 static var nm = 5 将解决问题,每次函数运行时您都会看到数字增加

继续挖掘其他帖子 (2nd answer),atlas.preload 似乎存在内存泄漏错误,发现预加载整个 SKTextureAtlas 的工作是调用类似

 for texture in self.textureNames {
        SKTexture(imageNamed: texture).size()
    }