2

I have a Dictionary of SKTextures that caches recently loaded textures (70 or so). I'm releasing them when a memory warning is received, like this:

let keys = textures.keys.array
for key in keys {
    textures[key] = nil
}

This works great, and I can see in the Xcode debugger that the memory is actually being freed.

When I try to release them on applicationDidEnterBackground(), however, it doesn't look like it fully works. The memory usage drops by a small inconsistent amount (5-20 MB), but the rest of it doesn't get freed until the app is resumed.

Is this a quirk with the debugger and the memory is being freed? Or does the garbage collector not have enough time to clean up before the app is suspended? Or am I doing this all wrong?

Update: I'm pretty sure it's related to SpriteKit automatically pausing the SKView when entering the background. This is easily reproducible by pausing the view manually just before releasing the textures. Then the memory won't be freed even when the memory warning is received.

Anterras
  • 21
  • 3
  • 1
    Side note: you should consider using `NSCache` for this. – Aaron Brager Nov 20 '14 at 23:13
  • iOS doesn't have a garbage collector; memory management is done at compile time. For more information, see [How does the new automatic reference counting mechanism work?](http://stackoverflow.com/q/6385212/3476191) – NobodyNada Nov 20 '14 at 23:23
  • I changed it from Dictionary to NSCache to see if it made a difference. It works just fine, but still has the same behavior when going to the background. – Anterras Nov 21 '14 at 00:00

1 Answers1

2

Is this a quirk with the debugger and the memory is being freed

I would describe it a quirk of how memory management works. There's a virtual memory management system. The memory is being freed but that doesn't mean that it is emptied / reclaimed, if you see what I mean. What you've done is to say that this memory is free, but the system won't take it unless it needs it.

The way to test is to write another app that deliberately gobbles memory, and run it while your app is in the background. Instruments will work even when you are suspended, and will show that in fact your memory usage goes down.

matt
  • 447,615
  • 74
  • 748
  • 977
  • I can see that being the case, but then why wouldn't it happen the same when the memory is released without going to the background? – Anterras Nov 21 '14 at 03:47
  • Regardless, I wrote another app that loads images continuously (I let it run until it had about 2 GB in memory), but the first app's usage didn't go down. How much memory does the second app need to allocate before I should see a change? – Anterras Nov 21 '14 at 04:06