Common Leaks when using Xib files

Xib (nib) files in Cocoa make memory leaks super easy, especially if you are coming from iOS Development. In iOS top level objects are autoreleased, but on the Mac it is the responsibility of the file’s owner to release them.

Fun fact if you don’t use something like NSWindowController or NSViewController you need to release all the top level objects in your nib or they will be leaked.

You can either create an outlet to each top level object individually and release them on dealloc or use -[NSNib instantiateNibWithOwner: topLevelObjects:] and keep track of the array of topLevelObjects. Managing the top level objects is not that bad, but something that can be easily forgotten.

Things get a bit trickier when you use ARC (automatic reference counting). Since you are not allowed to call release you either need to not use arc when loading nibs with top level objects or cast objects to a Core Foundation Type and use CFRelease.

Another leak I came across recently can occur when binding properties to the nibs File Owner. The problem with this is that it creates a retain cycle so the file owner will never be deallocated. The best advice I have seen on the subject came from Jeff Johnson which is definitely worth a read if you want more details about this topic. He recommends the following:

“Don’t use Cocoa bindings and nibs, because they’re teh suck.”

Unfortunately in my case the damage had already been done and so I choose to unbind programmatically when I knew the File Owner was going away. This breaks the retain cycle and everything gets cleaned up properly.


Now read this

Animating on the Apple Watch

This is a repost of an article I wrote for the company I work at, Tumult. Subtle animations are a great way to add fun and personality to an Apple Watch App. Whether its a custom loading indicator or part of a game, animations can bring... Continue →