强制 KVC 类型
我想解析 XML 以填充符合 KVC 的对象,但是我的解析器非常愚蠢,它只是从 XML 属性/标签组装 NSString 并尝试通过 KVC 设置它们。
这适用于实际的字符串和数字(我相信),但我还需要设置日期。问题显然是解析器不知道字符串代表日期,它尝试使用普通的 KVC 调用来放置它 - 之后 KVC 框架抱怨类型不匹配(在日期字段上设置字符串)。
是否有一种编程方式来“拦截”对 KVC 框架的调用,以便我可以更改正在设置的数据(通过 NSDateFormatter 运行日期字符串)?
我可以在解析器中加入一些智能,但在此之前,对于此类问题还有其他众所周知的解决方案吗?
I would like to parse XML to populate KVC compliant objects but, my parser is very dumb, it simply assembles NSStrings from the XML attributes/tags and tries to set them via KVC.
This works for actual strings and numbers (I believe) but I need to also set dates. The problem is obviously that the parser doesn't know the string represents a date and it tries to sit it using the vanilla KVC calls - afterwhich the KVC framework complains about the type mismatch (setting a string on a date field).
Is there a programmatic way to 'intercept' invocations into the KVC framework such that I can alter the data being set (run a date string through an NSDateFormatter)?
I could put some intelligence into the parser but before doing so, are there any other well-known solutions for this type of problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能不是完美的解决方案,但是......我想分享我的想法;)
所以,首先,看看这里:键值编码 - 验证。该文档描述了一种在通过 KVC 设置变量时验证变量的巧妙方法。您可以通过以下方式利用这一点:
这应该提供一个干净的实现来确保正确的类型。
干杯,
帕维尔
This might not be the perfect solution, but... I'd like to share my ideas ;)
So, first of all, take a look here: Key-Value Coding - Validation. That document describes a neat way to validate your variable the moment it's set via KVC. You could use this to your advantage by:
This should provide a clean implementation for ensuring proper type.
Cheers,
Pawel
使用 KVC,一切都会通过
setValue:forKey:
的默认实现来调用适当的 mutator 方法 (如此处所述)。您只需覆盖
setValue:forKey:
即可检查需要转换的一个或多个键,并进行适当的更改。这是来自内存的,因此不能保证它是否会真正编译和运行。 ;-)
With KVC, everything goes through a default implementation of
setValue:forKey:
whichs calls the appropriate mutator method (as described here).You can just override
setValue:forKey:
to check for the key or keys that need transforming, and make appropriate changes.That's from memory, so no guarantees whether it'll actually compile and run. ;-)