Create a view controller class and UI and add a button like this:

Then add the following code:

#import "ViewController1.h"

@implementation ViewController1

- (void)viewWillAppear:(BOOL)animated {
    NSLog(@"register for NoteFrom2");
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(handleNotification:)
     name:@"NoteFromTwo"
     object:nil]; 
}

- (IBAction)noteFrom2:(id)sender {
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"NoteFromTwo" 
     object:self];
}

-(void)handleNotification:(NSNotification *)pNotification
{
    NSLog(@"#1 received message = %@",(NSString*)[pNotification object]);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

That’s it! We register for notification in viewWillAppear (setting ourselves up as the observer) and then get notified (hanldeNotification) when a message of channel “NoteFromTwo” gets pumped out.

Don’t forget to remove yourself when your done watching:

  [[NSNotificationCenter defaultCenter] removeObserver:self];

Thanks to Julius for this post.

About these ads