Start a Project

What are KVO And Notification observers in swift?

Hello guys, Today we learn about “What are KVO And Notification observers in swift?”
Both methods use for observing the change in view.

Getting Started:-


KVO:-


Firstly we learn about KVO– what is KVO, and why do we use it?

KVO is a Key-Value Observing, It is a mechanism to notify the change in another object to enable the objects.
In Model-View-Controller it is use for communication between the objects.
When we want to use KVO observing pattern it require an object to confirm the KVO(NSKeyValueObserving) protocol. if your class is inherited by NSObject is automatically implement the KeyValueObserving Protocol.

How to register the KVO for observing?
Add Observer to receive The KVO notification.

In the keyPath section, notify your key name
To know about UnsafeMutableRawPointer, Please click here.

Calling of observer:-


Remove the observer: –


Notification Observer:-


Secondly, What is a Notification observer?
By using Notification observer we can send and receive any changes in event.
The most use of notification observer in push notification where we want to do some event on the click of notification.

How to use
Taking an example for notification click

Step 1:- firstly we need to post the notification observer in notification center function in app delegate


Step 2:- now add the observer in the controller where we want to perform the event

NotificationCenter.default.addObserver(self, selector: #selector(“Your Funtion Name“), name: NSNotification.Name(rawValue: “Your observer Name”), object: nil)

and last, create the function and do your code


How to remove observer:

Conclusion:-

In this blog, we discussed What are KVO And Notification observers in swift?
I hope this blog will help you to understand the flow of both methods (KVO and Notification centre)
To learn more about the iOS-related topic, Please click here.

Thanks For reading!!

Exit mobile version