Question

I'm trying all kinds of examples of NSNotificationCenter, but none of them are working. I have a UITableViewController that when a user clicks a cell, it opens a UIViewController that houses a WebView. Just to get the ball rolling, I'm trying to have the UITableViewController log a message that it received the notification when the UIViewController with the WebView loads. Here's what I have:

In MyTableViewController -

- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
 if (self) {

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveTestNotification:)
                                                 name:@"TestNotification"
                                               object:nil];
 }
 return self;
}


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

 if ([[notification name] isEqualToString:@"TestNotification"]) {
    NSLog (@"Successfully received the test notification!");
 }

}

- (void) dealloc
{

 [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Then in my UIViewController that has a webview in it, I have -

- (void)viewDidLoad
{
 [super viewDidLoad];

 [[NSNotificationCenter defaultCenter]
 postNotificationName:@"TestNotification"
 object:self];

 ....
}

When I run and touch a cell in the UITableviewController to open the UIViewController with a WebView, no log message. No crash, no nothing. What gives?

Any help is much appreciated.

EDIT

- (id)initWithCoder:(NSCoder *)aDecoder
{

 self = [super initWithCoder:aDecoder];
 if (self)
 {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveTestNotification:)
                                                 name:@"TestNotification:"
                                               object:nil];
 }

return self;
}
Was it helpful?

Solution

If you're using Interface Builder then initWithStyle: wont be called as your initializer, instead override initWithCoder:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top