开发者

How to override superclass' s NSNotificationCenter listener method?

Say I have superclass which listens to a notification:

@implementation SuperClass

- (v开发者_开发知识库oid)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
}

Now in a subclass, I want to do something different with that notification. The first thing I tried is to override foo:

@implementation SubClass
- (void)foo:(NSNotification *)notification
{
  //do something different
}

This does not work since the listening selector still points to superclass's method. Then I tried to remove superclass's listener and add from subclass:

@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
}

This doesn't work either, with or without cast/override. The notification event is still handled by superclass. I'm not sure how NSNotificationCenter handles observers from same address but of different pointer type. And I don't want to touch superclass. Can anyone please help?


Would this work?

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


Close this question by answering myself. The problem description should have stated clearly how NSNotificationCenter works with subclasses.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜