How to use NSNotificationCenter in Swift

Today we will learn How to use NSNotificationCenter in Swift, you may heard of it now you will implement it.

The difference between Objective C and Swift implementation is of syntax only.

NSNotificationCenter : it is an internal communication tool to your app. It provides a way for one instance of a class/struct to notify one or more other class/struct instances about something. You can also say its is like radio station broadcasting notification and we can add observers tuned to specific notification.

Dont confuse yourself with Delegates there is difference between both.

So lets start by Creating some notifications.

  1. Generating notification :


          You can generate different notification with different identifiers/key.

2. Adding observer to receive notification.


By doing this the we add an obser to notificationIdentifier whenever there will be any notification enerated by this identifier our observer will catch that. And method will be called whenever there is notification for that key.

3. Handling notification :

its just a simple function like we do in @selector(select)


4. Removing observer on notification :

This helps in memory managemant too remove your observer after they called up.

Removing Single notification observer


  Removing all observers


You saw that in Location updation when state changed I mainly used it in my model when there is new data it generate notification and that make other classes to act and use that data.

 Today we learn How to use NSNotificationCenter in Swift next time will come back with something exciting and helpful.

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.