Objective-C & KeyValueCoding: How to avoid an exception with valueForKeyPath:?

swalkner picture swalkner · Dec 19, 2011 · Viewed 7.1k times · Source

I've got an object of type id and would like to know if it contains a value for a given keyPath:

[myObject valueForKeyPath:myKeyPath];

Now, I wrap it into a @try{ } @catch{} block to avoid exceptions when the given keypath isn't found. Is there a nicer way to do this? Check if the given keypath exists without handling exceptions?

Thanks a lot,

Stefan

Answer

Richard J. Ross III picture Richard J. Ross III · Dec 19, 2011

You could try this:

if ([myObject respondsToSelector:NSSelectorFromString(myKeyPath)])
{
}

However, that may not correspond to the getter you have, especially if it is a boolean value. If this doesn't work for you, let me know and I'll write you up something using reflection.