我创建了NSObject扩展,以允许从PLIST或字典中包含的数据设置对象属性。我确实使用了setValuesForKeysWithDictionary
,但这仅适用于键,而不适用于keyPaths。除了允许PLIST包含键路径和键之外,我的扩展名执行相同的操作。例如,detailTextLabel.text @“ detailed text”作为键值对。
这很好用,但是由于PLIST中的错字可能导致应用程序崩溃。例如,如果属性名称存在但它是预期的其他类型(例如,数字而不是字符串),它将崩溃。使其更健壮和防御性代码避免此类错误的最佳方法是什么?
我已经在对象中使用- (void) setValue:(id)value forUndefinedKey:(NSString *)key {}
来捕获PLIST中与实际键不对应的项目。
#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];
}
}
预先感谢,戴夫。
最佳答案
在@try/@catch
周围添加了常规setValue:forKeyPath:
@try {
[self setValue:value forKeyPath:key];
}
@catch (NSException * e) {
NSLog(@"%@",e);
}
确实可以防止应用程序崩溃,但是我希望找到一种在选择设置其值之前检查选择器的方法。
如果没有更好的答案,将接受此答案。