NSNotification Selectors and Subclasses
// Don’t do this…
@interface parentViewController : UIViewController
@end
@implementation parentViewController
- (void) viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTheNotification:) name:@”MyNotificationName” object:nil];
}
- (void)handleTheNotification:(NSNotification *)note
{
NSLog(@”Parent selector”);
}
@end
@interface childViewController : parentViewController
@end
@implementation childViewController
- (void)viewDidLoad {
// update from my original post – as brought up in the comments I do call super in viewDidLoad
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HandleTheNotification:) name:@”MyNotificationName” object:nil];
}
- (void)handleTheNotification:(NSNotification *)note
{
NSLog(@”Override of parent selector”);
}
- (void)HandleTheNotification:(NSNotification *)note
{
NSLog(@”Stupid child notification that shouldn’t have been added”);
}
@end
// … the runtime will randomly call one or the other selector in you child class.
Shouldn’t both selectors be performed, but in an undefined order?
http://www.cocoabuilder.com/archive/cocoa/230712-nsnotificationcenter-multiple-messages-sent-to-the-same-observer.html
Randy Becker
January 5, 2011 at 6:21 am
Assuming your subclass’s -viewDidLoad invokes the superclass’s implementation. Otherwise, it should always only invoke the capitalized method.
Randy Becker
January 5, 2011 at 6:25 am
You’re right – my example is incorrect. I do call super in the child viewDidLoad…
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HandleTheNotification:) name:@”MyNotificationName” object:nil];
}
Nick Harris
January 5, 2011 at 6:27 am