2008 03 23KVC and KVO from a Javascript standpoint
Coming from Javascript, Key Value Coding (KVC) and Key Value Observing (KVO) will seem pretty familiar. KVC lets you handle your object just like a hash (NSDictionary in Cocoa terms), KVO sends a notification when a dictionary key has been changed.
Key Value Coding | |
Javascript | ObjC |
// Read a value alert(myObject['myValue']) // Set a value myObject['myValue'] = 123 |
// Read a value [myObject valueForKey:@"myValue"] // Set a value [myObject setValue:[NSNumber numberWithInt:123] forKey:@"myValue"] |
Key Value Observing | |
function callMeWhenMyValueChanged(newValue) { // Receiving the new value of myObject.myValue } // Setup a notification for when myObject.myValue changes myObject.__defineSetter__('myValue', callMeWhenMyValueChanged) // Set a value myObject['myValue'] = 123 |
// Add an observer for myObject's myValue [myObject addObserver:myObserverObject forKeyPath:@"myValue" options:0 context:nil]; // Set a value [myObject setValue:[NSNumber numberWithInt:123] forKey:@"myValue"] // When setting the new value, KVO calls myObserver's // observeValueForKeyPath:ofObject:change:context: |
Note the differences : in Javascript, a setter can be any function, even a global one. In ObjC, an observer function must be member of a class. In Javascript, you define the name of your function. In ObjC, the KVO notification has a fixed name (observeValueForKeyPath:ofObject:change:context
) — it's called a protocol, and it's the subject of the next post : ObjC protocols from a Javascript standpoint.
Objective-C from Javascript
- KVC and KVO from a Javascript standpoint
- ObjC protocols from a Javascript standpoint
- Delegates from a Javascript standpoint
- Target+action from a Javascript standpoint
- Outlets from a Javascript standpoint
- Dynamic method over* from a Javascript standpoint
- The Responder Chain from a Javascript standpoint
- PerformSelector from a Javascript standpoint
- NIBs from a Javascript standpoint
- Events from a Javascript standpoint