我正在上一个扩展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继承子类的情况下,它也不会调用析构函数。
所以解决方法是删除观察者,但是如何?
最佳答案
保存创建的观察者,然后在需要时将其删除并处理:
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();