Hey. I am reading in a string from a file and attempting to use the resulting string to set a BOOL property on an object using the KVC method -setValue:forKeyPath:
. However, this breaks with an exception: -[NSCFString charValue]: unrecognized selector sent to instance 0x7fff711023b0
. I'm guessing this is because BOOL is typedef'd from char. Is there a way around this? Thanks!
views:
40answers:
2
+1
A:
When setting a BOOL
property using KVC, you need to pass an NSNumber
object. What you could do in your case is pass [NSNumber numberWithBool:[myString boolValue]]
. That should fix your crash.
Dave DeLong
2010-09-07 22:37:43
Except I have no way of guaranteeing that what I am trying to access is a bool. Do you think it would be reasonable to catch the exception and then re-try using a wrapped version?
Grimless
2010-09-07 22:54:53
A:
I am catching the exception, checking it's name, and then retrying with a wrapped value when needed. Here is the code:
@try
{
[(NSObject*)retObj setValue:[[obj keyValuePairs] objectForKey:key]
forKeyPath:key];
}
@catch (NSException * e)
{
if ([[e name] isEqualToString:NSInvalidArgumentException])
{
NSNumber* boolVal = [NSNumber numberWithBool:[[[obj keyValuePairs] objectForKey:key] boolValue]];
[(NSObject*)retObj setValue:boolVal
forKeyPath:key];
}
}
Thanks anyway!
Grimless
2010-09-08 01:12:44