Preventing Cocoa bindings retain cycle

I ran into a problem using bindings programmatically. I found some of my bindings were preventing my views from being deallocated (see retain cycle). The culprit looked something like:
[child bind:@"frame" toObject:self withKeyPath:@"childFrame" options:nil];

There are two solutions I found:

  1. Calling a teardown method when your done with your view where you can perform cleanup.
  2. The second method, which I think is a little cleaner, basically involves binding through a proxy self object. It looks something like this:
    [child bind:@"frame" toObject:selfProxy withKeyPath:@"content.childFrame" options:nil];
    Since we are binding to a proxy, it doesn’t increment your view’s retainCount, thus preventing the retain cycle.  Setting the proxy NSObjectController.content to self does however increase your retainCount by 2, but we can handle that since it doesn’t change.

Check out this little utility that lets you investigate these two methods. It uses a cool little technique called Method Swizzling to show when dealloc gets called.

Check it out on Github: