SKTextureAtlas staying in memory

126 views Asked by At

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

2

There are 2 answers

0
KissTheCoder On BEST ANSWER

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()
    }
1
AbdAlWahab Fanr On

You're allocating and initializing a new texture every time you touch the screen which means you'll not have a reference the second time the function runs because it is getting replace by a new texture pointer

To solve this add static before the var declaration which will prevent the variable from being overwritten by a new pointer until the program finishes

e.g If you put in that function

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

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

nm is getting overwritten everytime putting static before declareing it static var nm = 5 Will solve the issue and you'll see the number increasing every time the function runs