iOS: Using NSNotificationCenter to Send/Receive Messages

Using NSNotificationCenter is a great way to send messages such that its corresponding receivers will be able to update their variables or interface values.

First, create a name for your notification in your Constants file (go here if you don’t know how to create one), or anywhere appropriate so that your receiver(s) and sender will be able to access it.
Put this into your .h (Header) file:
extern NSString * const kUpdateNotification;
And this into your .m (Implementation) file:
NSString * const kUpdateNotification = @"updateNumber";

On the receiver end, add the following into viewWillAppear and viewWillDisappear, and add a method updateThatNumber that receives the notification object from sender:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateThatNumber:) name:kUpdateNotification object:nil];

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kUpdateNotification object:nil];

- (void)updateThatNumber:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    NSInteger newNumber = [[userInfo objectForKey:kNewNumberKey] integerValue];
    self.thatNumber = newNumber;

This is the code for the sender, which will post the notification in some method:

NSDictionary *userInfo = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%d", newNumber], nil] forKeys:[NSArray arrayWithObjects:kNewNumberKey, nil]];
[[NSNotificationCenter defaultCenter] postNotificationName:kUpdateNotification object:self userInfo:userInfo];

Leave a Reply

Your email address will not be published. Required fields are marked *