What is responsible for releasing NSWindowController objects?

限于喜欢 提交于 2019-12-01 09:03:12

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1031715/what-is-responsible-for-releasing-nswindowcontroller-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!