Parmanoir

KVC 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
JavascriptObjC
// 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


Follow me on Twitter
Planet Cocoa
Cocoa.fr

2011 02 22Distance field
2010 07 202Binding through NSApp
2010 05 122Forwarding invocations
2010 02 272Core Image black fringes
2010 02 21Quickest Way to Shell
2010 02 08Who's calling ?
2009 09 2138 ways to use Blocks in Snow Leopard
2009 08 182Bracket Mess
2009 08 124Taming JavascriptCore within and without WebView
2009 04 15Debugging with Activity Monitor
2009 03 25How Core Image Color Tracking works
2009 03 1510Custom NSThemeFrame
2009 03 10Which framework is running ?
2009 03 074CoreUI can paint pretty big
2009 02 18Localization with functions
2009 01 30Did you forget to nest alloc and init?
2009 01 16JSCocoa on the iPhone
2009 01 11Mixing WebView and JavascriptCore
2009 01 09Badge overflow
2009 01 09Find your Garbage Collection leaks with Instruments

Powered by MediaWiki