說我有超類,它會監聽一個通知:如何覆蓋超類的NSNotificationCenter監聽器方法?
@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如何處理來自相同地址但不同指針類型的觀察者。我不想碰超類。任何人都可以幫忙嗎?
No-repro。當我按照你所描述的情況建立一個測試程序時,就像我所期望的那樣,簡單地覆蓋子類中的通知處理程序會導致被調用。 –
看到您的回覆,我重新檢查了我的代碼,發現導致問題的無關錯誤。之後,上述兩種方法都正常工作,NSNotificationCenter沒有問題找出哪個是哪個。感謝您的回覆! –
很高興聽到你想通了! –