Thursday, April 28, 2016

Objective C Key Value Observer (KVO) Tutorial-2

Why we need observers,
How to observe property changes,

by taking NSOperation properties as examples.

In this post, Let's take a real time practical example and discuss KVO in detail.

I am taking an example of Employee object, where his/her salary says whether that employee comes under tax or not. This clearly says, we need to observe for employee salary to play with his tax calculation.


I am taking an Employee class which is as shown below.

Employee class is having two properties here, salary and isTaxApplicable

isTaxApplicable is read only as it is depending on the salary. You can't set it's value from out side of this class as it is completely depends on the salary value.

But in my implementation file, I am going to write an extension as I need to change the access level of isTaxApplicable property inside my class as shown below.

In the extension, I have changed the property to readwrite as without which I can't set it's value inside my class.

If this 'extension' is sounding new/strange to you,

Please check out my tutorial Objective C Extensions and do come back here once you get an idea on Extensions topic in Objective C :)

We need to write the observer on salary property and in the observer delegate method, we need to change the isTaxApplicable property based on the salary value. So my whole class looks like below.

Nothing new here, If you have already gone throw my 

I have written an observer on salary property and observing the changes in the same class and changing the value of the isTaxApplicable property based on the salary value.

Here, one thing I want to discuss is the options parameter in addObserver and change parameter in the observeValueForKeyPath method.

NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld

I want both the values here. I mean old value of the salary as well as new salary.


Hope this post is useful. Feel free to comment incase of any queries.