I have have been trying to get NSNotification to work. For a test, I wanted a button that loads a new viewController using storyBoards. When you click the button it should trigger a notification for the appObserver to pick up in the second ViewController (I’ve named Page2). In Page2 the the NSNotificationCenter should launch a method (myMethod:) and print out a simple NSLog.
Unfortunately, it doesn’t work as myMethod does not get called. what am I doing wrong ???
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (IBAction)goToPage2Button:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
}
#import "Page2.h"
@interface Page2 ()
@end
@implementation Page2
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(myMethod:) name:@"test" object:nil];
}
return self;
}
-(void)myMethod:(NSNotification *)notification{
if ([[notification name] isEqualToString:@"test"])
NSLog (@"Successfully received the test notification!");
}
I think this could be because your page2 view controller does not exist when the notification is fired.
The second view controller registers for observation when it wakes from it’s nib, but if it hasn’t been created, then it hasn’t registered for the notification that your first view controller is sending.
What you should be doing is using segues to load view controllers based on actions.