Search code examples
iosobjective-crespondstoselector

respondsToSelector: returns true for selector but setValue:forKey: then fails due to undefined key


I am trying to utilise key-value coding to assign data to an instance of a small model class:

SEL selectorName = NSSelectorFromString(elementName);
if ([self.fixtureItem respondsToSelector:selectorName])
{
    [self.fixtureItem setValue:self.currentElementData forKey:elementName];
}

When elementName is 'description', respondsToSelector: returns true but setValue:forKey: then raises an NSUnknownKeyException:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key description.'

Why does respondsToSelector: return true but setValue:forKey: then report that the key 'description' is actually undefined?


Solution

  • Because you object does respond to the selector @selector(description) but does not respond to @selector(setDescription:), which is what setValue:forKey: will ultimately call.