iPhone app crashing with NSUnknownKeyException setValue:forUndefinedKey:

btw picture btw · Sep 5, 2008 · Viewed 28.7k times · Source

I'm writing my first iPhone app, so I haven't gotten around to figuring out much in the way of debugging. Essentially my app displays an image and when touched plays a short sound. When compiling and building the project in XCode, everything builds successfully, but when the app is run in the iPhone simulator, it crashes.

I get the following error:

Application Specific Information:
iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A331)
*** Terminating app due to uncaught exception 'NSUnknownKeyException', 
reason: '[<UIView 0x34efd0> setValue:forUndefinedKey:]: this class is not key value 
coding-compliant for the key kramerImage.'

kramerImage here is the image I'm using for the background.

I'm not sure what NSUnknownKeyException means or why the class is not key value coding-compliant for the key.

Answer

amrox picture amrox · Sep 5, 2008

(This isn't really iPhone specific - the same thing will happen in regular Cocoa).

NSUnknownKeyException is a common error when using Key-Value Coding to access a key that the object doesn't have.

The properties of most Cocoa objects can be accessing directly:

[@"hello world" length]    // Objective-C 1.0
@"hello world".length      // Objective-C 2.0

Or via Key-Value Coding:

[@"hello world" valueForKey:@"length"]

I would get an NSUnknownKeyException if I used the following line:

[@"hello world" valueForKey:@"purpleMonkeyDishwasher"]

because NSString does not have a property (key) called 'purpleMonkeyDishwasher'.

Something in your code is trying to set a value for the key 'kramerImage' on an UIView, which (apparently) doesn't support that key. If you're using Interface Builder, it might be something in your nib.

Find where 'kramerImage' is being used, and try to track it down from there.