说我有超类听取通知:
@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如何处理来自相同地址但具有不同指针类型的观察者。而且我不想触及超类。有人可以帮忙吗?
答案 0 :(得分:0)
这会有用吗?
[[NSNotificationCenter defaultCenter] removeObserver:[self superclass] name:@“bar”object:nil];
答案 1 :(得分:0)
通过自己回答来关闭这个问题。问题描述应该清楚地说明NSNotificationCenter如何与子类一起使用。