Search code examples
iphonenotificationsnsnotificationcenternsnotifications

How to post and receive an NSNotifications (Objective C) | Notifications (in Swift)?


Is there an easy-to-grock pattern how to send a NSNotification (Objective C) | Notification (in Swift) and how to receive one? Code snippet? The docs write like 150 pages on the topic. Would like to see a quick example.


Solution

  • Send a notification:

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

    Receive it:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cacheUpdated:) name:@"MyCacheUpdatedNotification" object:nil];
    

    Act on it:

    - (void)cacheUpdated:(NSNotification *)notification {
    [self load];
    }
    

    And dispose of it:

    [[NSNotificationCenter defaultCenter] removeObserver:self];