mardi 16 octobre 2012

Key-Value Coding

Key-Value Coding is a way to access an object's property indirectly. Rather than using an accessor, you'll be able to use a string to identify a property. From that simple idea, you will get a powerful mechanism, allowing, for instance, observing, binding, collection operators etc.


Key and KeyPath

So, a Key is a string that identifies the name of an accessor method, or of an instance variable, in the receiving object. The valueForKey: method, part of the NSKeyValueCoding informal protocol, will return the value for the specified Key, relative to the receiver.
For example:
[person valueForKey:@"age"];
will invoke the age method of the person object.

Now let's me introduce the KeyPath. KeyPath is simply a string of dot separated Keys, used to specify a sequence of properties to traverse. Each property, in a KeyPath, is relative to the value of the previous property, or relative to the receiver for the first one. The valueForKeyPath: method returns the value for the specified KeyPath, relative to the receiver.
For example:
[person valueForKeyPath:@"father.age"];
will invoke the age method on the object returned by the father method of the person object.

Collection Operators

With KeyPaths comes a great tool named Collection Operators that allow actions to be performed on the items of a collection using KeyPath notation. For example you will be able to retrieve the max value in a collection, or the sum, the average, etc. Official doc here.

This is really great, but the problem is that those operators retrieve the final value of a keyPath, and not the object for which the keyPath gives the value matching the operator. To satisfy this lack, i have created a github : Collections+KeyPath which allow to retrieve the max or the min object in a collection given a keyPath. For example, if you have a collection of persons, you may use:
[persons maxObjectForKeyPath:@"father.age"];
which will retrieve the person that have the oldest father.

Key-Value Observing

Observing's principle is to warn a delegate as soon as a property's value has changed. Observing (KVO for the friends) is a very well known and documented subject within the Cocoa world. Official doc here to learn more.

Binding

Based on the Key-Value Observing, binding's aim is to link properties of different objects together, so that if any of the binded properties change, its new value is immediately and automatically propagated to the other property. Bindings are available on OS X since the Panther version (10.3, released in 2003), but has never been brought to iOS. In order to fill this gap, i started a new github : STBinding.

Aucun commentaire:

Enregistrer un commentaire