Search code examples
swiftmemorymemory-managementsprite-kitsktextureatlas

SKTextureAtlas staying in memory


I made a quick project to understand how SpriteKit frees atlases from memory. Every time the screen is tapped an atlas is created and is loaded into memory. The only reference to the atlas is what you see in the code below and I thought since the var is inside a non-escaping function that it doesn't hold a strong reference. My goal was for the previous atlases loaded into memory to be freed eventually, however memory piles up and eventually crashes.

I understand atlases are only supposed to be loaded in once and the three points Apple makes here (Working with Sprites) about why textures wouldn't be freed

Could someone help me understand why this is the case?

class GameScene: SKScene {

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

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

        atlas?.preload {

            atlas = nil

            print("Loaded")

        }

    }

}

enter image description here A new stair of memory is created each time a touch is detected


Solution

  • Went digging for other posts (2nd answer) and there seems to be a memory leak bug with atlas.preload and found the work around to pre-load the entire SKTextureAtlas is to call something like

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