1

說我有超類,它會監聽一個通知:如何覆蓋超類的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如何處理來自相同地址但不同指針類型的觀察者。我不想碰超類。任何人都可以幫忙嗎?

+0

No-repro。當我按照你所描述的情況建立一個測試程序時,就像我所期望的那樣,簡單地覆蓋子類中的通知處理程序會導致被調用。 –

+0

看到您的回覆,我重新檢查了我的代碼,發現導致問題的無關錯誤。之後,上述兩種方法都正常工作,NSNotificationCenter沒有問題找出哪個是哪個。感謝您的回覆! –

+0

很高興聽到你想通了! –

回答

0

通過回答我自己的問題來關閉此問題。問題描述應該明確說明NSNotificationCenter如何與子類一起工作。

0

這項工作?

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

+1

'[self superclass]'是一個'Class'對象,而不是一個實例,對吧? – zoul

+0

那麼,如果你有一個超類的實例的引用,那麼你可以使用它作爲「觀察者」參數removeObserver方法。 – Zhang