TruMan1 TruMan1 - 1 year ago 111
Swift Question

Possible reasons for memory leaks in iOS?

I'm researching possible memory leak traps in iOS and I keep coming across strong reference cycles. This has become clear and the only thing mentioned that I can find regarding memory leaks, even in Apple's documentation.

What are some other causes for memory leaks to avoid?

Rob Rob
Answer Source

In Objective-C, there are many types of leaks that the static analyzer (shift-command-B) can help identify. Beyond simple strong reference cycles, if you're not using ARC with Objective-C, it's extremely easy to leak. And if you're using Core Foundation objects (especially in Objective-C) and aren't careful, you can easily leak. The static analyzer is pretty good at identifying many of these simple issues.

But stepping back a little, Apple discusses three types of common memory problems:

  • Leaked memory: Memory that can't be accessed again.

    Examples of this would be incorrect bridging of Core Foundation types, strong reference cycles, etc.

  • Abandoned memory: Memory that won't be accessed again.

    An example of this would be a circular reference in view controllers (from A to B and to A again, rather than popping/dismissing back to A). The original A view controller still exists and could theoretically access its objects, but you won't ever do so, because you're now working with a new instance of A.

  • Cached memory: Memory that can be accessed again (but for which you may or may not actually access it again).

    An example of this would be using imageNamed with UIImage, which caches the image in case you need it again in the future, whether you actually do or not.

    Proper caching mechanisms will respond to memory pressure and purge the cache in these situations. But failure to do so can cause unbounded growth in memory.

I'd suggest watching a few WWDC videos including:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download