Nick Harris

NSNotification Selectors and Subclasses

with 3 comments

// 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.

Advertisements

Written by Nick Harris

January 5, 2011 at 3:06 am

Posted in Uncategorized

3 Responses

Subscribe to comments with RSS.

  1. 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

  2. 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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: