Pages

Monday 9 February 2015

Key Value Coding and Key Value Observing


Key Value Coding:
Key value coding is a mechanism which helps us to access the properties of an object indirectly by name (or key, which is a string) rather than directly using the accessor method. The key value coding cannot be confused with the NSDictionary’s keys.

For e.g. the UITextField has a property called text which gives the current text displayed in it.
You normally access it by calling the following accessor method of the UITextField.
[myTextField setText:@"Hello"];
NSLog(@"%@", myTextField.text);
The above statements can be re-written by using the Key-Value coding as follows.
[myTextField setValue:@"Hello" forKey:@"text"];
NSLog(@"%@", [myTextField valueForKey:@"text"]);
The KCV can also be nested.
For e.g
[self.view setBackgroundColor:[UIColor blackColor]];
can be replaced with
[self setValue:[UIColor redColor] forKeyPath:@"view.backgroundColor"];
Key Value Observing:
Key-value observing is a mechanism that allows objects to be notified of changes to specified properties of other objects
For e.g. The UITextfield has delegate whenever it’s text changes, but it doesn’t have the delegates to inform about it’s colour changes. You can observe those with the “Key Value Observing”.
When you add an object as an observer for a textfield for it’s text property, whenever the text value of the textfield changes, the observer method of the object is called with the arguments.
    [myTextField addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    NSLog(@"%@ \t %@ \t %@", keyPath, object, change);
}
The KVC can be used for our custom objects by default. You don’t have to do anything separately to support the KVC i.e
[myObject setValue:@"Hello" forKey:@“foo”];
will work if the myObject have a property called foo.
But to support KVO for your custom objects you have to make use of the following methods inside object's class.
[self willChangeValueForKey: @"foo"];
[self didChangeValueForKey: @"foo"];

KVC and NSArray:
NSArray has some amusing functions with KVC's. You can see them in the following screenshot.



ScreenShot:



KVC in Xib:

     You can use the KVC directly in the Xib also. See the following screenshot. I have changed the corner radious of a view directly in the Xib itself. No coding needed. You can do the same for your own custom objects too.




Notes:
    If the object doesn't have the key you passed, the setValue:forKey: will raise an exception. 
    The keys are case sensitive.
    The KVC is little slower.

References:



No comments:

Post a Comment