顯示包含「KVC」標籤的文章。顯示所有文章
顯示包含「KVC」標籤的文章。顯示所有文章

2010年12月8日星期三

KVC for BOOL type not working

Recently I tried to read xml files by KVC in order to get rid of the frustrating hard-coded name matching.

However, by using the  -setValue:forKeyPath: function, I got a "-[NSCFString charValue]: unrecognized selector sent to instance XXXXXX" error when it comes to setting value of any property of BOOL type.

I could only found a few reference on Stackoverflow.

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

Since I am not knowing the type until runtime, I need to catch the exception before converting the data type. But I am not sure whether any other type would cause the same exception and lead to an incorrect casting.

I haven't met any problem yet, and hopefully it is safe