KVC string conversion not working for BOOL value

依然范特西╮ 提交于 2019-11-29 15:42:39

问题


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!


回答1:


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.




回答2:


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!




回答3:


Add a simple category to your project:

@implementation NSString (CharValue)

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

@end


来源:https://stackoverflow.com/questions/3663266/kvc-string-conversion-not-working-for-bool-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!