我已经创建了一个对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];
}
}提前谢谢你,戴夫。
发布于 2011-08-04 18:57:45
我在setValue:forKeyPath:周围添加了一个通用的@try/@catch
@try {
[self setValue:value forKeyPath:key];
}
@catch (NSException * e) {
NSLog(@"%@",e);
}这确实可以防止应用程序崩溃,但是我希望找到一种在尝试设置选择器的值之前检查选择器的方法。
如果没有更好的答案,我会接受这个答案。
https://stackoverflow.com/questions/6646971
复制相似问题