views:

122

answers:

1

Is there any way to detect when an NSView will be dealloc'ed?

The reason is, I have some simple delegates (such as an NSTextField delegate that handles -control:textView:doCommandBySelector: to allow the return/tab keys to be entered). I'd like to just stick this delegate object in the nib, wire up the NSTextField's delegate connection and have it work.

And it does work, but the delegate is never released even after the NSTextField it is linked to is released, so the delegate object leaks.

I'd like the delegate object to be able to detect when the NSTextField is dealloc'ed, but I can't think of any way to do this, which leaves me having to store a separate link to the delegate object from some other controller and manually release it at some point which is very much less than ideal. Any ideas?

+1  A: 

I've had a good look for this previously, and there doesn't appear to be any way to observe when an object is deallocated. I have seen one way to do it in a weak pointer class, but it involves isa swizzling, which can get nasty. Here is the website: http://www.cocoadev.com/index.pl?WeakPointers

Objects that are created from a nib file should be deallocated when the owner of the nib is deallocated, unless they are retained elsewhere. For example, when an NSWindowController is deallocated it will release any objects that were created when the nib was loaded. If your delegate objects aren't being deallocated, maybe it's because they are retained elsewhere, or there is a retain cycle.

Tom Dalling
The problem is I didn't want to have to add code to each controller to know about and delete this NSTextField-specific delegate which it otherwise would have no interaction with. My solution was to use a superclass controller with 5 (ick) IBOutlet ivars releaseOnDealloc1..5. In the superclass, dealloc calls release on each of those ivars. Then in Interface Builder, for each view I just hooked up and extraneous objects to the various releaseOnDealloc outlets to have them released at the appropriate time. A bit ugly, but effective with minimal code/effort.
Peter N Lewis