KEY VALUE CODING AND KEY VALUE OBSERVING

Sai Charitha
8 min readJul 11, 2019

--

Introduction:

In programming, one of the most commonly accepted facts is that the flow of a program depends on the value of the various variables and properties you use.Think of how many times you need to check if an object has been added to an array, or if it has been removed from it. So, being aware of the changes that happen to the properties of your classes is a vital part of the programming process.

There are various ways that let us be notified when a property gets changed. For example, if you have a method to set a property’s value, or you just override a setter method, you can send a notification (NSNotification) to notify an observer about that change, and then perform the proper actions based on the value that was set.

There is a much better way to observe for changes in properties, and Apple uses it a lot in its own software.This method is called Key-Value Observing, but is mostly known as KVO.

Key-Value Observing is related directly to another powerful and important mechanism, named Key-Value Coding, or KVC.

Key-Value Coding(KVC) and Key-Value Observing(KVO) are really powerful concepts found throughout Apple’s frameworks. They allow you to write code more dynamically and even observe and act accordingly when properties in your classes change.This can be really useful, because you can do anything when a property changes, including but not limited to check if its value is valid, send a message to someone when something changes to a certain value and so on. The options are unlimited.

Key-Value Coding (KVC) and Key-Value Observing (KVO) are keys when writing Mac OS X applications. Cocoa Bindings allow you to wrap your variables with Cocoa objects and this is done via KVC and KVO.Cocoa Bindings are really powerful and very easy to work with.

Key Value Coding (KVC):

KVC is a form of coding that allows you to access an object’s properties indirectly, using strings to access them instead of the property’s accessors or instead of accessing the variables directly.Instead of directly setting the value to the property or use the setter method of the property, we simply match values to keys or key paths . As we use keys and values, this technique is called Key-Value Coding.

To enable such mechanism, your classes must comply to the NSKeyValueCoding informal protocol. NSObject complies with it and it also has default implementations of its methods, so most of the time you won’t need to modify anything in order to use KVC.

  • Key: The key specifies a single property, the one we want to set a value to or get one from, so its name should be similar to the property’s one.
  • Key Path: A key path is always formed using the dot syntax, so it’s not a single word, and represents all the properties of an object that should be traversed until the desired one is found (speaking totally non-technically so as to make things clear, I would say that the key path looks for the sub- property of the sub-property of the … (and so on) … of an object).

KVC allows you to do KVO: That is, if you are observing a variable, you will only be notified of its changes if and only if the changes take place using KVC. If you modify a variable directly using its setter you are not going to be notified of its changes.

Let’s suppose that we have a property named first name, and we want to assign the value John to it. Normally, what we would write in code to do it is this:

self.first name = @“John”;

Now, using the KVC mechanism the above assignment would look like the next one:

[self setValue:@”John” forKey:@“first name”];

If you look closely, this looks similar to the way we set values to dictionaries, or when converting scalar values and structs to NSValue objects. As you see, we set the value John for the key first name.

KVC Approaches:

There are five key-value coding approaches.They are:

1.KVC approach1-NSKeyValueCoding Protocol:

This category implements the setValue:forKey: and valueForKey: methods that you can use for setting and getting values by NSString keys.

2.KVC approach2-Manual subsets of NSKeyValueCoding behaviour:

The NSKeyValueCoding protocol looks up methods by selector names and looks up ivars by name.This approach allows you to define your own lookup path.

3.KVC approach3-Associated Objects:

The Objective-C 2.0 runtime (used on the iPhone and 64-bit Mac OS X apps) allows you to set any object to be associated with any other object. This allows any object in the runtime to have an arbitrary set of extra properties set by key, without support from ivars or methods on the object itself.

The main reason why you would use this approach is that you want to set properties on an object from the outside — i.e. without the object supporting, being involved with or even knowing about the property access. Properties can be set on an object by other parts of the program for their own purposes.

4.KVC approach4-Selectors as keys:

Key-value coding is primarily about looking up a property for a key and then acting upon the property found during lookup.Objective-C has a lookup at its very core — the method lookup. The keys for this lookup are selectors.

This approach is similar to manually implementing the method part of NSKeyValueCoding but rather than forming a selector string from the key and then looking up the selector string, this approach opts to use the selector as the key.

The disadvantage this approach has is that separate selectors are needed for getting and setting.

5.KVC approach5- Do it yourself:

The final approach to key-value coding is to handle the implementation yourself. This is something you would do if you needed maximum flexibility (for handling unusual keys/values) or wanted to expose different key-value sets from a single object.The easiest way to do this is to expose a getter and a setter method and simply get or set the values on a dictionary contained by the object. To handle the internal storage of the values, you could use any of the key-value storage structures in Cocoa

  • NSMutableDictionary
  • NSMapTable
  • CFMutableDictionaryRef

Key Value Observing (KVO):

Key-value observing is a mechanism that allows objects to be notified of changes to specified properties of other objects.It is particularly useful for communication between model and controller layers in an application.A controller object typically observes properties of model objects, and a view object observes properties of model objects through a controller. In addition, however, a model object may observe other model objects .

You can observe properties including simple attributes, to-one relationships, and to-many relationships. Observers of to-many relationships are informed of the type of change made — as well as which objects are involved in the change.

A simple example illustrates how KVO can be useful in your application.Suppose an Employee object interacts with a Details object, representing the employee details at office. An instance of Employee may need to be aware of when certain aspects of the Details instance change, such as the employee id, or the phone number.

If these attributes are public properties of Details, the Employee could periodically poll the Details to discover changes, but this is of course inefficient, and often impractical. A better approach is to use KVO, which is akin to Employee receiving an interrupt when a change occurs.

To use KVO, first you must ensure that the observed object, the Details in this case, is KVO compliant. Typically, if objects inherit from NSObject and you create properties in the usual way, objects and their properties will automatically be KVO Compliant. It is also possible to implement compliance manually. KVO Compliance describes the difference between automatic and manual key-value observing, and how to implement both.

Next, you must register your observer instance, the Employee, with the observed instance, the Details. Employee sends an addObserver:forKeyPath:options:context: message to the Employee, once for each observed key path, naming itself as the observer

In order to receive change notifications from the Details, Employee implements the observeValueForKeyPath:ofObject:change:context: method, required of all observers. The Details will send this message to the Employee any time one of the registered key paths changes. The Employee can then take appropriate action based upon the change notification.

Finally, when it no longer wants notifications, and at the very least before it is deallocated, the Employee instance must de-register by sending the message remove Observer:forKeyPath: to the Details.

Registering for Key-Value Observing describes the full lifecycle of registering for, receiving, and de-registering for key value observation notifications.

KVO’s primary benefit is that you don’t have to implement your own scheme to send notifications every time a property changes. Its well-defined infrastructure has framework-level support that makes it easy to adopt — typically you do not have to add any code to your project. In addition, the infrastructure is already full-featured, which makes it easy to support multiple observers for a single property, as well as dependent values.

Registering Dependent Keys explains how to specify that the value of a key is dependent on the value of another key.

Unlike notifications that use NSNotificationCenter, there is no central object that provides change notification for all observers. Instead, notifications are sent directly to the observing objects when changes are made. NSObject provides this base implementation of key-value observing, and you should rarely need to override these methods.

Conclusion:

Key Value Coding is one of the best code patterns for reducing repetitious code and making classes more reusable by decoupling actions from properties and data.Key Value Observing can be a powerful substrate in which abstractions can be built easily.So, use of KVC and KVO in your application makes code easy in an efficient way.

--

--