Cocoa NSWindowController И NSWindow Not Deallocing



Я работаю с NSWindowController для реализации окна настроек. В документации Apple говорится, что по умолчанию контроллер и окно не освобождаются, потому что полезно не перезагружать все, что имеет смысл. Но в их документации говорится, что вы можете переопределить это поведение, но не объясняете, как это сделать.



Документы Apple:



When a window is closed and it is part of a document-based
application, the document removes the window’s window
controller from its list of window controllers. This results
in the system deallocating the window controller and the
window, and possibly the NSDocument object itself. When a
window controller is not part of a document-based application,
closing the window does not by default result in the
deallocation of the window or window controller. This is the
desired behavior for a window controller that manages something
like an inspector; you shouldn’t have to load the nib file
again and re-create the objects the next time the user requests
the inspector.

If you want the closing of a window to make both
window and window controller go away when it isn’t
part of a document, your subclass of NSWindowController
can observe the NSWindowWillCloseNotification notification
or, as the window delegate, implement the windowWillClose: method.


Я не могу найти нигде, что объясняет, что нужно "реализовать"в методе windowWillClose:.



Окно контроллер можно посмотреть здесь:
https://github.com/gngrwzrd/gwpreferences/blob/master/GWPreferences/GWPreferences/GWPreferences/GWPrefsWindowController.m



Использование контроллера можно посмотреть здесь:
https://github.com/gngrwzrd/gwpreferences/blob/master/GWPreferences/GWPreferences/GWAppDelegate.m- вы можете видеть в этом коде, где я пытаюсь применить некоторые мосты, чтобы попытаться принудительно освободить объекты, но это не работает.



Итак, GWPrefsWindowController.метод dealloc никогда не звонит. Есть идеи?

590   1  

1 ответ:

Я понимаю, что этот вопрос стар, но для тех, кто пришел сюда из google, ответ довольно прост.

Как указано в документации, для недокументных базовых приложений вы можете просто:

  • держите ссылку для вашего NSWindowController, где бы вы его ни называли. (В приведенном ниже примере на него ссылается myWindowController;
  • заставьте класс, вызывающий ваш NSWindowController, реализовать протокол NSWindowDelegate;
  • освободите контроллер окна, установив его на ноль в методе windowWillClose:

Чтобы точнее ответить на этот вопрос. При ленивом создании экземпляра контроллера задайте класс в качестве делегата:

-(IBAction)showMyWindowAction:(id)sender
{
    // If my window controller is not nil
    if (!myWindowController)
    {
        //instantiate it
        myWindowController = [[MyWindowController alloc] initWithWindowNibName:@"myWindow"];
        // set your class as delegate
        [myWindowController setDelegate:self];
     }

     [myWindowController.window orderFront:self];
}

И затем реализовать метод windowWillClose: из протокола NSWindowDelegate

-(void)windowWillClose:(NSNotification *)notification
{
     //Check if it's the right window that will close
     if ([notification.object isEqualTo:myWindowController.window])
     {
         //Set your controller to nil
         myWindowController = nil;
      }
}

Вот и все, ваш оконный контроллер теперь освободится, и поскольку мы проверяем, является ли он контроллером nil, прежде чем показывать окно, все будет работать!

Я считаю, что причина, по которой это не реализовано по умолчанию, заключается в том, что initWithWindowNibName: является несколько тяжелым таким образом, вы должны думать, если dealloc'ING все, что находится на вашем окне, повлияет больше или меньше, чем загрузка вашего файла window nib.

Надеюсь, это помогло

Comments

    Ничего не найдено.