【问题标题】:How to override superclass' s NSNotificationCenter listener method?如何覆盖超类的 NSNotificationCenter 监听器方法?
【发布时间】:2011-11-28 22:06:48
【问题描述】:

假设我有一个监听通知的超类:

@implementation SuperClass

- (void)viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(foo:) name:@"bar" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
  [super viewWillDisappear:animated];
  [[NSNotificationCenter defaultCenter] removeObserver:self name:@"bar" object:nil];
}

- (void)foo:(NSNotification *)notification
{
  //do something
}

现在在一个子类中,我想对该通知做一些不同的事情。我尝试的第一件事是覆盖 foo:

@implementation SubClass
- (void)foo:(NSNotification *)notification
{
  //do something different
}

这不起作用,因为监听选择器仍然指向超类的方法。然后我尝试删除超类的监听器并从子类中添加:

@implementation SubClass
- (void)viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated];
  [[NSNotificationCenter defaultCenter] removeObserver:(SuperClass *)self name:@"bar" object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(foo2:) name:@"bar" object:nil];
}

- (void)foo2:(NSNotification *)notification
{
  //do something different
}

无论有没有强制转换/覆盖,这都不起作用。通知事件仍由超类处理。我不确定 NSNotificationCenter 如何处理来自相同地址但指针类型不同的观察者。而且我不想接触超类。有人可以帮忙吗?

【问题讨论】:

  • 无复制。当我使用您描述的情况设置测试程序时,只需覆盖子类中的通知处理程序就会导致调用它,正如我所期望的那样。
  • 看到你的回复,我重新检查了我的代码,发现了一个不相关的错误导致了这个问题。之后,上述两种方法都可以正常工作, NSNotificationCenter 可以毫无问题地确定哪个是哪个。感谢回复!
  • 很高兴听到你想通了!

标签: objective-c overriding selector observer-pattern nsnotificationcenter


【解决方案1】:

这行得通吗?

[[NSNotificationCenter defaultCenter] removeObserver:[self superclass] name:@"bar" object:nil];

【讨论】:

  • [self superclass] 将是一个 Class 对象,而不是一个实例,对吧?
  • 好吧,如果你有一个对你的超类实例的引用,那么你可以将它用作 removeObserver 方法的“observer”参数。
【解决方案2】:

通过回答我自己来结束这个问题。问题描述应该清楚地说明 NSNotificationCenter 如何与子类一起工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多