Question

Lets say I display a window like so:

[[TBAddTaskWindowController new] showWindow:self];

Where is the TBAddTaskWindowController object meant to be released? Is the generic solution to call [self release] in windowWillClose?

It doesn't feel right to have any other object "own" the window, because it's meant to exist until the user closes it.

Was it helpful?

Solution

The same code that instantiated the window controller by sending the new message to the class, just the same as if it had done it by alloc and init messages.

OTHER TIPS

Yes, a common way to do release the window controller is with:

- (void)windowWillClose:(NSNotification *)notification
{
    [self autorelease];
}

The Window Controller needs to live only as long as the window is around, so autoreleasing it when the window goes away makes perfect sense.

Remember to remove any other observers, etc as well.


[added information for working under ARC]

For ARC, you need to retain a strong reference to the window control while the window is open, and then remove it when the window closes.
To do this, I added a category on the window controlled with two methods:

  • pnl_addWindowController — called by the window controller when the window is first opened
  • pnl_removeWindowController — called from windowWillClose

The category maintains a global NSMutableSet of active window controllers. The code is essentially just [gWindowControllers addObject:self] and [gWindowControllers removeAllObjects], with some lazy creation of the NSMutableSet and some locking.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top