强制KVC类型 [英] Coercing a KVC type

查看:96
本文介绍了强制KVC类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析XML来填充符合KVC的对象,但是我的解析器非常笨拙,它只是从XML属性/标记中组合NSString并尝试通过KVC设置它们.

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.

这适用于实际的字符串和数字(​​我相信),但我还需要设置日期.问题显然是解析器不知道该字符串代表一个日期,而是尝试使用普通的KVC调用来放置它-之后,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).

是否存在一种编程方式来拦截"对KVC框架的调用,以便我可以更改正在设置的数据(通过NSDateFormatter运行日期字符串)?

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?

推荐答案

这可能不是完美的解决方案,但是...我想分享我的想法;)

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:

  1. 首先为您的类变量实施KV验证方法
  2. 设置您的价值
  3. 在您的验证方法中,检查它是否是日期/字符串/您想要的任何内容-并将其更改为正确的类型.

这应该提供干净的实现以确保正确的类型.

This should provide a clean implementation for ensuring proper type.

干杯, 帕维尔

这篇关于强制KVC类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆