提高 setValueForKeyPath 的稳健性
我创建了 NSObject 的扩展,以允许从 PLIST 或字典中包含的数据设置对象属性。我确实使用了 setValuesForKeysWithDictionary ,但这仅适用于键,不适用于 keyPaths。我的扩展做了同样的事情,除了允许 PLIST 包含键路径和键之外。例如,detailTextLabel.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];
}
}
预先感谢,戴夫。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
setValue:forKeyPath:
周围添加了一个通用的@try/@catch
这确实可以防止应用程序崩溃,但是我希望找到一种检查选择器的方法在尝试设置其值之前。
如果没有更好的答案,将接受这个答案。
Have added a general
@try/@catch
around thesetValue:forKeyPath:
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.