What is to post to notification center mean? What is the difference between to post and to add observer using NotificationCenter.
NSNotificationCenter : NSNotificationCenter can be consider as an interface used for communicating information within your app.Unlike push or local notifications where you are notifying a user of any content you would like them to receive, NSNotificationCenter allows us to send and receive information between classes and/or structs based on an action that has occurred in our app. NotificationCenter simply can be thought of an broadcaster and we tune into some stations/channels to receive the changes if any.
NotificationCenter.default is where all the notifications are observed and posted.Each notification has a unique identifier which can be used to validate the channel at broadcasting end as well as receiving end.
addObserver() : Objects register with a notification center to receive notifications using the addObserver(_:selector:name:object:) or addObserver(forName:object:queue:using:) methods. When an object adds itself as an observer, it specifies which notifications it should receive. An object may therefore call this method several times in order to register itself as an observer for several different notifications.The class implementing the addobserver() method is reciever.
Example : Adding an observer(this is will at the receiving end)
NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
@objc func methodOfReceivedNotification(notification: Notification){}
post() : Creates a notification with a given name and sender and posts it to the notification center. Creating a package and send it through the channel. The class implementing the post() method is broadcaster.
Example : Posting an observer(this is will at the broadcasting end)
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
Note that the "NotificationIdentifier" is the unique name to identify the particular channel. And selector is method/action that need to be performed when a notification is received.You can also pass the data within the notification center within the "object" parameter.
"With respect to your question "What is the difference between to post and to add observer using NotificationCenter."
The answer is they both go head to head, one (add-observer()) is used to send and another one (post()) is used to receive. so if you are posting a notification its must that you should implement an observer too.In short if you throw something you need someone to catch, if you speak, you need someone to listen.