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

dontWatchMyProfile picture dontWatchMyProfile · Apr 20, 2010 · Viewed 18.9k times · Source

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.

Answer

Paul Lynch picture Paul Lynch · Apr 20, 2010

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];