KVC string conversion not working for BOOL value

孤街浪徒 提交于 2019-11-30 10:20:59

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.

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!

Add a simple category to your project:

@implementation NSString (CharValue)

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

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