Search code examples
iosnsnotificationcenternsnotifications

Observer on NSNotificationCenter that can handle multiple notifications


I have an observer lets call it Subscriber and I want to have it registered on NSNotificationCenter like so:

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
                    selector:@selector(post:)
                    name:nil
                    object:nil];

Where post: is:

- (void)post:(NSNotification *)notification {
    if (notification == nil) {
        // Throw an exception
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:nil object:nil];
}

I would like to extend Subscriber and create classes like PictureSubscriber and then post notifications to the PictureSubscriber and have it handle multiple types of notifications like so:

PictureViewController

[[NSNotificationCenter defaultInstance] postNotification:@"UpdatePictureNotification" object:self userInfo:urlDict];

...

[[NSNotificationCenter defaultInstance] postNotification:@"DeletePictureNotification" object:self userInfo:urlDict];

Then ideally what I would like is for PictureSubscriber to be able to receive different types of NSNotifications. How would I accomplish this?


Solution

  • //create contstant strings

    #define kUpdatePictureNotification @"UpdatePictureNotification"
    #define kDeletePictureNotification @"DeletePictureNotification"
    #define kReasonForNotification @"ReasonForNotification"
    #define kPictureNotification @"PictureNotification"
    

    // to post a notfication call this method and give the reason either kUpdatePictureNotification or kDeletePictureNotification

    -(void)postNotificationGivenReason:(NSString *)reason
    {
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
                              reason, kReasonForNotification,
                                // if you need more stuff add more
                              nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:kPictureNotification object:nil userInfo:dict];
    
    }
    

    // Here is the observer:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pictureNotification:) name:kPictureNotification object:nil];
    

    // here is the action method for pictureNotification

    -(void)pictureNotification:(NSNotification *)aNotification
    {
        NSString *reason = [aNotification.userInfo objectForKey:kReasonForNotification];
        if ([reason isEqualToString:kUpdatePictureNotification])
        {
            // It was a UpdatePictureNotification
        }
        else
        {
            // It was a DeletePictureNotification
        }
    }