Как удалить NSNotificationObserver Xamarin - PullRequest
0 голосов
/ 23 октября 2018

У меня есть класс, расширяющий ReactiveWindowController.Как и в базовом классе, я вижу это:

// subscribe to listen to window closing
// notification to support (de)activation
NSNotificationCenter
   .DefaultCenter
   .AddObserver(NSWindow.WillCloseNotification, 
       _ => deactivated.OnNext(Unit.Default), this.Window);

Следовательно, в моем подклассе я пишу обратный вызов для удаления наблюдателя, как

public partial class SplitViewWindowController : ReactiveWindowController
{

    ~SplitViewWindowController()
    {
        Console.WriteLine("Destructor of SplitViewWindowController");
    }

    public SplitViewWindowController() : base("SplitViewWindow")
    {
        Console.WriteLine("Constructor of SplitViewWindowController");

        this.Deactivated.Take(1).Subscribe(x => {

           // NSNotificationCenter.DefaultCenter.RemoveObserver(NSWindow.WillCloseNotification);

            // NSNotificationCenter.DefaultCenter.RemoveObserver(this);

            //NSNotificationCenter.DefaultCenter.RemoveObserver(Owner);

        });
    }

Но я потерялся, чтобы найти подходящий способудалить Наблюдателя.Или я здесь что-то не так делаю?

Почему я удаляю Обозреватель?Ответ в том, что SplitViewController не освобождается, если какой-либо наблюдатель остается незарегистрированным.Я попытался с NSWindowController, здесь, если все наблюдатели удалены, освобождение работает и распечатывает логи деструктора.Если я не удаляю наблюдателя даже в случае создания подкласса из NSWindowController, он не вызывает деструктор.

Так что исправление состоит в том, чтобы удалить наблюдателя, но как?

1 Ответ

0 голосов
/ 23 октября 2018

Сохраните созданного наблюдателя, а затем удалите и утилизируйте его при необходимости:

var observer = NSNotificationCenter.DefaultCenter.AddObserver(NSWindow.WillCloseNotification, HandleAction);
// You can also use the helper method...
// var observer = NSWindow.Notifications.ObserveWillClose(HandleEventHandler);

NSNotificationCenter.DefaultCenter.RemoveObserver(observer);
observer.Dispose();
...