Key-Value Observing mechanism simplified

The aim of this post is to show how it works Key-Value Observing mechanism (KVO). KVO is a mechanism for transparently notifying observers of changes in object properties. In other words,  this mechanism will allow us to trap when some object property value is being modified.

Implementation

We will create a class that will hold the property to be observed:

Its implementation is the following:

As you can see the property is set to 3 in the class initialiser. Now we are going to implement the KVO mechanism in the ViewController. We will add the observer in the viewDidLoad Method:

As important as setup the observer is remove it when it is not necessary, I will add it in the dealloc method:

In the viewWillAppear method I will update property that is being observed:

The callback that is being called every time that the property is changed is the following:

When you will run the project you will see that the above function is called twice. Once during NewObject initialisation and the other during viewDidAppear.

kvo

And in the log screen:

You can download the code from here.

 

 

Leave a Reply

Your email address will not be published.