KVC字符串转换不适用于BOOL值 [英] KVC string conversion not working for BOOL value

查看:147
本文介绍了KVC字符串转换不适用于BOOL值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿.我正在从文件中读取字符串,并尝试使用结果字符串使用KVC方法-setValue:forKeyPath:在对象上设置BOOL属性.但是,这会中断,但例外:-[NSCFString charValue]: unrecognized selector sent to instance 0x7fff711023b0.我猜这是因为BOOL是从char类型定义的.有没有解决的办法?谢谢!

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!

推荐答案

我正在捕获异常,检查它的名称,然后在需要时使用包装的值重试.这是代码:

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];
        }
    }

还是谢谢!

这篇关于KVC字符串转换不适用于BOOL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆