作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经为 NSObject 创建了一个扩展,以允许从 PLIST 或字典中包含的数据设置对象属性。我确实使用了 setValuesForKeysWithDictionary
但这只适用于键而不是 keyPaths。我的扩展做了同样的事情,除了允许 PLIST 包含 key 路径和 key 。例如,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];
}
}
提前致谢,戴夫。
最佳答案
在 setValue:forKeyPath:
@try/@catch
@try {
[self setValue:value forKeyPath:key];
}
@catch (NSException * e) {
NSLog(@"%@",e);
}
这确实可以防止应用程序崩溃,但是我希望找到一种在尝试设置选择器值之前检查选择器的方法。
如果没有更好的答案,将接受这个答案。
关于ios - 提高 setValueForKeyPath 的鲁棒性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6646971/
我已经为 NSObject 创建了一个扩展,以允许从 PLIST 或字典中包含的数据设置对象属性。我确实使用了 setValuesForKeysWithDictionary 但这只适用于键而不是 ke
我是一名优秀的程序员,十分优秀!