Can someone explain in simple terms what is Key-Value-Coding
and Key-Value-Observing
? Please don't provide links to Apple Developer's reference Document. I have gone through them. I expect an explanation in very simple terms.

- 5,020
- 4
- 49
- 75

- 12,099
- 23
- 89
- 155
-
2This is The best for it.. http://www.slideshare.net/sergio.acosta/intro-to-cocoa-kvckvo-and-bindings-presentation – iPatel Jul 16 '14 at 10:04
5 Answers
Key-Value-Coding (KVC) means accessing a property or value using a string.
id someValue = [myObject valueForKeyPath:@"foo.bar.baz"];
Which could be the same as:
id someValue = [[[myObject foo] bar] baz];
Key-Value-Observing (KVO) allows you to observe changes to a property or value.
To observe a property using KVO you would identify to property with a string; i.e., using KVC. Therefore, the observable object must be KVC compliant.
[myObject addObserver:self forKeyPath:@"foo.bar.baz" options:0 context:NULL];

- 25,520
- 5
- 61
- 71
-
2
-
2@Jacob Relkin One of the Darrens should be `darren *darrenB = &darrenA;` :) – alex Nov 26 '10 at 05:03
-
No, but it looks like we're both from the same town, answering the same questions, at the same time... What are the odds? – Darren Nov 26 '10 at 05:06
-
That is *so* weird. And with roughly the same amount of rep and badges. Hmmmmmmmmm..... – Jacob Relkin Nov 26 '10 at 05:27
-
2
-
addObserver is used to tell the other object to inform that "observer" (in this case, whatever 'self' refers to) when this property changes. It will call -observeValueForKeyPath:... on the observer when that happens. That way you can e.g. update your user interface when that property changes, so it displays the current value. BTW -- it is a very bad idea to pass NULL as the context to addObserver. – uliwitness Apr 10 '14 at 09:15
-
I have a confusion over here and doubt as well. What does this line means **Therefore, the observable object must be KVC compliant.** Is it like to observe a change in property via KVO, that object value must be set through KVC only. Because I tried it by myself and it is not so. If we will just set the value like **self.name=@"new name"**, then also it goes inside **-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context** – Hemant Sharma Aug 06 '14 at 17:47
Key Value Coding is simply accessing a property of an object through a string instead of the literal syntax.
// Here is a new instance of an object
Foo *foo = [[Foo alloc] init];
// Accessing a property called someValue with literal syntax:
[foo someValue];
// Accessing the same property with dot notation
foo.someValue;
// Accessing the same property with Key-Value coding:
[foo valueForKey:@"someValue"];
The power of KVC is that you can specify any arbitrary string at runtime (obviously this could be very dangerous too).

- 15,340
- 19
- 71
- 102
-
6Hi, could you please flesh this out that one final step--I do not understand the "power" of KVC yet. I understand that I could say [carObject valueForKeyPath:@"changePriceToFree"] but that property (changePriceToFree) has to pre-exist already for me to use KVC. So why not just call the property? I understand that I can vary the key that I am calling in my code at runtime, but I still don't know how I could apply this fact in real life. I assume this is a core topic that ios devs should know. Thanks! – user798719 Apr 03 '13 at 22:39
-
This is an outstanding explanation. However, I would also echo user798719's question of why is KVC so powerful, and why would this be used instead of using calling the property using literal or dot notation? Thanks! – daspianist Jun 21 '13 at 02:58
-
7@user798719 (and @daspianist), imagine you have a database where you have stored your Objective-C objects. You now need to retrieve an object. Instead of manually getting each field and manually storing it into the new object (via the dot or literal syntax), you could loop through each field in the database and call setValue:ForKey: on the object. Ex: You have an object "Person" with properties "name" and "bio". Your database has fields "name" and "bio". Since the names are the same, you can loop through the database fields and call setValue:ForKey: (with field name) on a new "Person" object. – tjklemz Sep 06 '13 at 22:23
Key-value coding allows you to fetch or change a property of an object using a string, at runtime, instead of needing to write code that is compiled to a fixed property from the start:
NSNumber* foo = [myPopup valueForKey: @"selectedItemIndex"];
[myPopup setValue: @15 forKey: @"selectedItemIndex"];
A good example for this is NSTableView on Mac, where you can just set an identifier on every table column that corresponds to your model object's property that it should display, and then your data source just calls -valueForKey:/-setValue:forKey: with the column's identifier as the key and the values pretty much display/set themselves. You just add the right columns to the table view in the XIB.
Key-value observing was added afterwards, and lets you register to be notified about changes made to another object. You register your interest by doing:
void* gMyKVOContext = &gMyKVOContext; // global variable somewhere that guarantees us a unique address that doesn't collide with a subclass's registration for observing the same property
...
[interestingObject addObserver: interestedObject forKeyPath: @"interestingProperty" options: 0 context: gMyKVOContext];
Whenever that property is changed, -observeValueForKeyPath:ofObject:change:context: will be called on the object you specified as the observer. So you'd implement that like:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if( context == gMyKVOContext && [keyPath isEqualToString: @"interestingProperty"] )
{
// Update UI that shows interestingProperty
}
else
[super observeValueForKeyPath: keyPath ofObject: object change: change context: context];
}
The advantage here is that you get called live the moment that other property is changed. Note that objects have to do a little work so these notifications are sent, so not all properties are key-value-observable. Also note that some objects may be in an invalid state if two related properties get changed right after the other: You get notified after the first property has been changed, which now contradicts the second, and only then the second property is changed and you're notified for that. So during that first observer callback, the object may be in a weird state, so be careful how you react to that.
To make a property observable, either use the default @synthesized implementation when you define it, or if you define it yourself, implement the setter like:
-(void) setFoo: (int)inFoo
{
[self willChangeValueForKey: @"foo"];
_foo = inFoo;
[self didChangeValueForKey: @"foo"];
}
Then always go through the setter to change it, don't change _foo directly. If you have related properties that could contradict each other like the above, a good way to avoid this is to always change them both in pairs (you can't use KVC then, though). To do that, implement a combined setter like:
-(void) setFoo: (int)inFoo bar: (int)inBar
{
[self willChangeValueForKey: @"foo"];
[self willChangeValueForKey: @"bar"];
_foo = inFoo;
_bar = inBar;
[self didChangeValueForKey: @"bar"];
[self didChangeValueForKey: @"foo"];
}
That way, both notifications are sent while the properties are in proper states.

- 8,532
- 36
- 58
Key-value coding is a mechanism for accessing an object’s properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables.

- 17,438
- 13
- 70
- 88

- 16,861
- 7
- 32
- 46
-
9From the original question "Please don't provide links to Apple Developer's reference Document." – Johan Karlsson Oct 03 '13 at 18:52
Objective-C Key Value Coding(KVC) vs Key Value Observing(KVO)
[Swift Key Value Coding (KVC)]
KVC
allows you to access to property by String, it is enabled for all NSObject successors(children). It adds a dynamism in the language. You can consider your class as Dictionary(Key-Value). It is an alternative/not-direct solution to assign/read/write variables
[valueForKey vs valueForKeyPath]
//preseudocode
class ClassA {
variableB: ClassB
}
objectA = ClassA()
ClassB *objectB = [objectA valueForKeyPath:@"variableB"];
KVC
is used by KVO
, as well as CoreData, Cocoa bindings...
KVO
allows you to subscribe on value changed. It is working for dynamic dispatch
//Objective-C
[objectA addObserver:self forKeyPath:@"variableB" options: NSKeyValueObservingOptionNew context:NULL];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
//logic
}
//Swift
objectA.observe(\.variableB, options: .new) { (object, change) in
//logic
}

- 29,217
- 8
- 193
- 205