Cocoa: Making Properties KVO Compliant

Posted: November 14th, 2009 | Author: Remi | Filed under: Cocoa, Programming | 1 Comment »

In Cocoa KVO or Key-Value-Observing compliant means that the value of a certain object sends notifications out when its value has been changed to an observer. An example would be values stored in a NSMutableDictionary or NSMutableArray. Since they are KVO compliant, you can bind something to a value in one of these objects, and will be updated automatically, no glue code required. Although not all objects have their values KVO compliant and this can cause problems for example when trying to bind to them in Interface Builder. A good example can be seen with NSDocument’s documentName. Notice you can bind an object’s value to documentName, but if the documentName changes, this value does not update. The way to fix this, is to subclass NSDocument and send out notifications whenever documentName is changed. A class-dump of NSDocument reveals the -(BOOL)_setDocumentName:(NSString*)name method. All you have to do is add this method to your NSDocument subclass

-(void)_setDisplayName:(NSString*)name
{
	//Hack Display Name to make KVO Compliant
	[self willChangeValueForKey:@"displayName"];
	[(YourClassNameHere*)super _setDisplayName:name];
	[self didChangeValueForKey:@"displayName"];
}

And that should be it. Note: I changed the method’s return type to void because otherwise it will create an error in the console about KVO compliant methods not being able to return anything other then void.

Also note that this is for read-only binding, to do a binding where you can change the value you have to implement and expose a new binding programmatically.

Apple’s Documentation on KVO