Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 450
dontWatchMyProfile Avatar asked Apr 20 '10 15:04

dontWatchMyProfile


People also ask

How do I use notification observer in Swift?

First, register an observer for a notification with: addObserver(_:selector:name:object:) Then, post a notification with post(name:object:userInfo:) … … after which your selector is called. And don't forget to remove the observer with removeObserver()

What is Nsnotificationcenter in IOS?

A notification dispatch mechanism that enables the broadcast of information to registered observers.

What is addObserver in Swift?

addObserver(forName:object:queue:using:) Adds an entry to the notification center to receive notifications that passed to the provided block.


1 Answers

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]; 
like image 53
Paul Lynch Avatar answered Oct 15 '22 19:10

Paul Lynch