objective-c – 子类中的NSNotificationCenter addObserver

我注册在超类(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
}

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

解决方法

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

You can override this method to perform additional tasks associated with presenting the view. If you override this method,you must call super at some point in your implementation.

所以你的通知设置很好(尽管将一个NSNotification对象作为你希望被覆盖的方法的参数有点奇怪) – 但是你要调用[super notification:notification]以获得超类的行为.

相关文章

我正在用TitaniumDeveloper编写一个应用程序,它允许我使用Ja...
我的问题是当我尝试从UIWebView中调用我的AngularJS应用程序...
我想获取在我的Mac上运行的所有前台应用程序的应用程序图标....
我是一名PHP开发人员,我使用MVC模式和面向对象的代码.我真的...
OSX中的SetTimer在Windows中是否有任何等效功能?我正在使用...
我不确定引擎盖下到底发生了什么,但这是我的设置,示例代码和...