Search code examples
iosobjective-cmemorymemory-leaksretain-cycle

iOS Memory management, (leaks, retain cycles)


I have some general questions about what happens to app memory.

  1. What happens to memory when the app enters the background or suspended. I'm asking this because my app has some memory leaks that are, from my research, bugs in Apple's framework and not due to my coding. The leaks are fairly small, (~100bytes), so they should not disrupt performance. However, I was wondering what happens to these leaks when the user stops using the app? Do they go away or do they just stay forever in the phone's memory?

  2. Also, another very similar question, except with retain cycles. Do retain cycles get resolved when a user quits an app, assuming they are not a big of a problem to crash the app while in use?

So, in short, when a user quits an app, do allocations and memory get reset to 0, is what I'm trying to ask.

Thanks for your help!


Solution

  • The answer is complicated.

    An app can be in a variety of states:

    Active
    Inactive
    Running in the background
    
    Suspended 
    
    Not running
    

    In all but the "not running" state, the app is in memory and your memory leaks continue to accumulate.

    Normally, when your user presses the home button, the app quickly transitions through inactive (still running in the foreground but no user interaction) to background (still running but another app has focus) and to suspended (in memory, but not getting any processor time. Your code isn't being called at all in this state.) You get a notification as the app moves to inactive and to the background state, before it goes to the suspended state.

    You're expected to save whatever information you need to save in response to the applicationDidEnterBackground message.

    Once the app is in the suspended state it can be terminated without any further warning. If you haven't saved your information to a file at that point, it's lost.

    If the app stays in the suspended state and then gets woken up to one of the running states, all of your in-memory objects are still around, and your memory leaks are still accumulating.

    As @blobbfuesch says, memory leaks cause your app to use up more and more of the device's RAM. If your memory use gets to be too much, the system will issue you one or more memory warnings, and if you don't free up enough memory, it will terminate you.

    Because leaked memory is lost, you CAN'T free it up. Even small leaks add up. If the user keeps your active long enough, they accumulate and can cause your app to be terminated, which looks like a crash to the user.

    If the app is terminated while in the suspended state, it gets unloaded from memory and has to be relaunched the next time it's run. in that case the previously leaked memory gets recovered, but then it starts leaking again.