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.
1 |
addObserver(self, forKeyPath keyPath: String?, of object: Any change: [Any?], context: UnsafeMutableRawPointer?) |
In the keyPath section, notify your key name
To know about UnsafeMutableRawPointer, Please click here.
Calling of observer:-
1 2 3 |
Override func addObserver(forKeyPath keyPath: String?, Option: NSKeyValueObservingOption = [.old, .new], context: UnsafeMutableRawPointer) { // Enter your code } |
Remove the observer: –
1 2 3 |
deinit { removeObserver(self, forKeyPath: #KeyPath) } |
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
1 |
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "Your observer Name"), object: nil, userInfo: userInfo) |
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
1 2 3 |
func <strong>Your Funtion Name</strong>(_ note: Notification) { // Add your code } |
How to remove observer:
1 2 3 |
deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name("Your observer name"), object: nil) } |
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.