NSNotificationCenter addObserver在子类中

时间:2012-12-19 20:50:42

标签: objective-c cocoa subclass superclass nsnotifications

我注册在超类(UIViewController)中被通知如下:

SuperClass.m

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(notification:)
                                                 name:@"Notification"
                                               object:nil];
}

- (void)notification:(NSNotification *)notification {

    // Do something for SuperClass with the notification
}

现在在子类(SuperClass.m的子类)中,我也像这样听取相同的通知:

SubClass.m

- (void)notification:(NSNotification *)notification {

    // Do something specific for SubClass with the notification
}

这是一种可接受的(代码方式)方法,用于处理超类中的通知时的一般行为,以及在处理子类中的通知时具有更具体的行为吗?

1 个答案:

答案 0 :(得分:2)

通常,当您希望在子类中允许更具体的行为时,仍然保持超类中的一般行为,您可以调用子类super。例如,-[UIViewController viewDidAppear:]文档说:

  

您可以覆盖此方法以执行与显示视图相关的其他任务。如果您覆盖此方法,则必须在实施中的某个时刻调用super

所以你的通知设置很好(虽然把NSNotification对象作为你期望被覆盖的方法的参数有点奇怪 - 但你要调用[super notification:notification]来获得超类的行为。