KVC string conversion does not work for BOOL value

Hey. I am reading a line from a file and trying to use the resulting line to set the BOOL property for an object using the KVC -setValue:forKeyPath: method. However, this breaks with the exception: -[NSCFString charValue]: unrecognized selector sent to instance 0x7fff711023b0 . I guess this is because BOOL is typedef'd from char. Is there any way around this? Thanks!

+3
source share
3 answers

I get an exception by checking its name, and then repeat if necessary with a wrapped value. 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]; } } 

Thank you anyway!

+3
source

When setting the BOOL property using KVC, you need to pass an NSNumber object. What you could do in your case is pass [NSNumber numberWithBool:[myString boolValue]] . This should fix your failure.

+3
source

Add a simple category to your project:

 @implementation NSString (CharValue) - (BOOL)charValue { return [self isEqualToString:@"0"] ? NO : YES; } @end 
0
source

All Articles