Objective c 如何重写超类的NSNotificationCenter侦听器方法?
假设我有一个监听通知的超类:Objective c 如何重写超类的NSNotificationCenter侦听器方法?,objective-c,overriding,selector,observer-pattern,nsnotificationcenter,Objective C,Overriding,Selector,Observer Pattern,Nsnotificationcenter,假设我有一个监听通知的超类: @implementation SuperClass - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(foo:) name:@"bar" object:nil]; } - (void)viewWillDisapp
@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 defaultCenter]removeObserver:[自超类]名称:@bar对象:nil] 通过回答自己来结束这个问题。问题描述应该清楚地说明NSNotificationCenter如何处理子类。[self superclass]将是一个类对象,而不是一个实例,对吗?如果您获得了对超类实例的引用,那么您可以使用它作为观察者参数来移除观察者方法。No-repro。当我按照您描述的情况设置测试程序时,只需重写子类中的通知处理程序就可以调用它,正如我所期望的那样。看到您的答复,我重新检查了代码,发现了一个导致问题的无关bug。在上述两种方法都很好地工作之后,NSNotificationCenter就可以确定哪种是哪种了。谢谢回复!很高兴听到你明白了!