开发者

Improving setValueForKeyPath robustness

I have created an extension to NSObject to allow for object properties to be set from data contained in a PLIST or dictionary. I did use setValuesForKeysWithDictionary but this only works for keys not keyPaths. My extension does the same thing, except allows the PLIST to contain key paths as well as keys. For example, detailTextLabel.text @"detailed text" as the key value pair.

This works well, except i开发者_运维问答t is possible to crash the app because of a typo in the PLIST. For instance, it will crash if the property name exists but is a different type that expected (a number instead of a string for instance). What is the best way to make this more robust and code defensively to avoid these types of errors?

I am already using - (void) setValue:(id)value forUndefinedKey:(NSString *)key {} in my objects to trap items in the PLIST that don't correspond to actual keys.

#pragma mark -
#pragma mark Extensions to NSObject

@implementation NSObject (SCLibrary)

- (void) setValuesForKeyPathsWithDictionary:(NSDictionary *) keyPathValues {
    NSArray *keys;
    int i, count;
    id key, value;

    keys = [keyPathValues allKeys];
    count = [keys count];
    for (i = 0; i < count; i++)
    {
        key = [keys objectAtIndex: i];
        value = [keyPathValues objectForKey: key];

        [self setValue:value forKeyPath:key];
    }
}

Thanks in advance, Dave.


Have added a general @try/@catch around the setValue:forKeyPath:

@try {
    [self setValue:value forKeyPath:key];
}
@catch (NSException * e) {
    NSLog(@"%@",e);
}

Which does prevent the app from crashing, however I was hoping to find an approach that checked for the selector before trying to set its value.

Will accept this answer if a better one is not forthcoming.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜