0

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 it 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.

4

1 に答える 1

3

@try/@catchの周りに将軍を追加しましたsetValue:forKeyPath:

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

これはアプリのクラッシュを防ぎますが、値を設定する前にセレクターをチェックするアプローチを見つけたいと思っていました。

より良い答えが来ていない場合は、この答えを受け入れます。

于 2011-08-04T10:57:45.333 に答える