iPhone workshop frequently asked question: Key Value Coding error

By Elisabeth Robson
July 1, 2009

One of the most common questions from the iPhone workshops we held recently is: "What is key value coding and why the heck am I getting this error?"

This error being something like:

2009-07-01 15:50:55.423 AppName[1169:20b] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<AppNameAppDelegate 0x524f60> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key aboutviewController.'

This error usually crops up when you've changed an outlet in your source code, but you haven't updated your nib file to re-wire the outlet.

I got the error above when I originally created my code with an outlet referencing a view controller named aboutviewController from my app delegate, and used Interface Builder to connect the outlet properly. Later, I modified the name of my controller in my app delegate source code to aboutViewController, but forgot to update the nib file. The code compiled just fine, but I get the runtime error because when the application attempts to set up the connections I set up using IB, the name of the outlet no longer matches the name specified in the nib file.

A common cause of this error is misspelling the name of an outlet when you first create it and then fixing the spelling later, or when you're refactoring your code and realize that another name for the outlet variable would be more appropriate.

So what is Key Value Coding and how is this error related to it? Apple describes Key Value Coding as a way to access an object's properties using strings to identify those properties. The nib file loading process uses it to programmatically set up the connections you've specified using Interface Builder. The names in the nib file must match the names in your code exactly, or the nib loading process will fail when it attempts to find the properties (outlets) you've referenced in the nib file. And of course, this matching process is case sensitive, so even a small mistake like typing aboutviewController instead of aboutViewController will cause this error.

You can also use Key Value Coding in your own code to simplify and generalize it (the Apple documentation page referenced above provides an example), which I haven't done yet, but I can definitely see why it would be useful.

You might also be interested in:

News Topics

Recommended for You

Got a Question?