알림을 수신하는 수퍼 클래스가 있다고 가정 해 보겠습니다.수퍼 클래스의 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는 어떤 문제인지 파악하는 데 아무런 문제가 없습니다. 답변 감사합니다! –
당신이 그것을 알아 낸 것을 듣고 다행! –