NSNotificationCenter addObserver in a subclass

I register for notification in the superclass (UIViewController) as follows:

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 } 

Now in the subclass (subclass of SuperClass.m) I also listen to the same notification:

SubClass.m

 - (void)notification:(NSNotification *)notification { // Do something specific for SubClass with the notification } 

Is this an acceptable (code) way to have general behavior when acting on a notification in a superclass and have more specific behavior when acting on a notification in a subclass?

+4
source share
1 answer

Usually, when you want to allow more specific behavior in a subclass, while preserving the general behavior in the superclass, you call the superclass super . For example, the documentation -[UIViewController viewDidAppear:] says:

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

So, your notification setting is great (although it’s a little strange to have an NSNotification object as a parameter to the method you expect to override), but you want to call [super notification:notification] to get the superclass behavior as well.

+2
source

All Articles