239

In the Mac and iOS platforms, memory leaks are often caused by unreleased pointers. Traditionally, it has always been of utmost importance to check your allocs, copies and retains to make sure each has a corresponding release message.

The toolchain that comes with Xcode 4.2 introduces automatic reference counting (ARC) with the latest version of the LLVM compiler, that totally does away with this problem by getting the compiler to memory-manage your stuff for you. That's pretty cool, and it does cut lots of unnecessary, mundane development time and prevent a lot of careless memory leaks that are easy to fix with proper retain/release balance. Even autorelease pools need to be managed differently when you enable ARC for your Mac and iOS apps (as you shouldn't allocate your own NSAutoreleasePools anymore).

But what other memory leaks does it not prevent that I still have to watch out for?

As a bonus, what are the differences between ARC on Mac OS X and iOS, and garbage collection on Mac OS X?

0

5 Answers 5

263

The primary memory-related problem you'll still need to be aware of is retain cycles. This occurs when one object has a strong pointer to another, but the target object has a strong pointer back to the original. Even when all other references to these objects are removed, they still will hold on to one another and will not be released. This can also happen indirectly, by a chain of objects that might have the last one in the chain referring back to an earlier object.

It is for this reason that the __unsafe_unretained and __weak ownership qualifiers exist. The former will not retain any object it points to, but leaves open the possibility of that object going away and it pointing to bad memory, whereas the latter doesn't retain the object and automatically sets itself to nil when its target is deallocated. Of the two, __weak is generally preferred on platforms that support it.

You would use these qualifiers for things like delegates, where you don't want the object to retain its delegate and potentially lead to a cycle.

Another couple of significant memory-related concerns are the handling of Core Foundation objects and memory allocated using malloc() for types like char*. ARC does not manage these types, only Objective-C objects, so you'll still need to deal with them yourself. Core Foundation types can be particularly tricky, because sometimes they need to be bridged across to matching Objective-C objects, and vice versa. This means that control needs to be transferred back and forth from ARC when bridging between CF types and Objective-C. Some keywords related to this bridging have been added, and Mike Ash has a great description of various bridging cases in his lengthy ARC writeup.

In addition to this, there are several other less frequent, but still potentially problematic cases, which the published specification goes into in detail.

Much of the new behavior, based on keeping objects around as long as there is a strong pointer to them, is very similar to garbage collection on the Mac. However, the technical underpinnings are very different. Rather than having a garbage collector process that runs at regular intervals to clean up objects no longer being pointed to, this style of memory management relies on the rigid retain / release rules we all need to obey in Objective-C.

ARC simply takes the repetitive memory management tasks we've had to do for years and offloads them to the compiler so we never have to worry about them again. This way, you don't have the halting problems or sawtooth memory profiles experienced on garbage collected platforms. I've experienced both of these in my garbage collected Mac applications, and am eager to see how they behave under ARC.

For more on garbage collection vs. ARC, see this very interesting response by Chris Lattner on the Objective-C mailing list, where he lists many advantages of ARC over Objective-C 2.0 garbage collection. I've run into several of the GC issues he describes.

5
  • 2
    Thanks for the detail answer. I had the same issue where I defined a delegate under _unsafe_unretained and got my application crashed, later fixed it by changing to strong but now it has a memory leak. So, I changed it to weak and works like a charm.
    – chathuram
    Jan 22, 2013 at 19:59
  • @ichathura Wow! You saved me from the ARC mire. I've encountered the same crash when using CMPopTipView.
    – Nianliang
    Jun 28, 2013 at 15:46
  • @BradLarson: "you don't have the halting problems or sawtooth memory profiles experienced on garbage collected platforms". I'd expect worse halting and sawtooth memory profiles from scope-based reclamation and much worse performance from reference counting so I'd like to see a real comparison.
    – J D
    Apr 16, 2016 at 13:08
  • Brad, the link from Chris Lattner is dead. I'm not 100% but I found this other link. Which I think is what you wanted to link to: lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160208/…
    – mfaani
    Oct 6, 2018 at 16:06
  • 1
    @Honey - Thanks for pointing that out. The one you link is slightly different, but I replaced the dead link with an archived version of the original message. It's in mailing list archives, which should be available somewhere, but I'll look to see if I can find their new location.
    – Brad Larson
    Oct 8, 2018 at 14:14
14

ARC won't help you with non-ObjC memory, for example if you malloc() something, you still need to free() it.

ARC can be fooled by performSelector: if the compiler can't figure out what the selector is (the compiler will generate a warning on that).

ARC will also generate code following ObjC naming conventions, so if you mix ARC and MRC code you can get surprising results if the MRC code doesn't do what the compiler thinks the names promise.

0
7

I experienced memory leaks in my application due the following 4 issues:

  1. Not invalidating NSTimers when dismissing view controllers
  2. Forgetting to remove any observers to NSNotificationCenter when dismissing the view controller.
  3. Keeping strong references to self in blocks.
  4. Using strong references to delegates in view controller properties

Luckily I came across the following blog post and was able to correct them: http://www.reigndesign.com/blog/debugging-retain-cycles-in-objective-c-four-likely-culprits/

0

ARC will also not manage CoreFoundation types. You can 'bridge' them (Using CFBridgingRelease()) but only if you are going to use it as an Objective-C/Cocoa object. Note that CFBridgingRelease just decrements the CoreFoundation retain count by 1 and moves it to Objective-C's ARC.

0

Xcode 9 provides a great tool for finding that kind of issues. It is called: "Debug Memory Graph". Using it you can find your leaked object by class type and you can see clearly who holds a strong reference to it, by releasing it from there solves your problem. It is also detects memory cycles.

See more info about how to use it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.