键值编码
当我启动一个简单的 iPhone 应用程序时,我采用了一种直接的方法将 XML 摘录的键/值对转换为 NSDictionary。 问题是,我需要将那些曾经填充我的 UITableView 的 NSDictionary 实例转换为自定义类,因为它们需要行为和额外的复杂性。 这里的问题是,现在要实例化一个对象并使用来自 Web 服务的键/值对填充其实例变量变得更加困难。 我不能再将其放入迭代 XML 并使用 KVC 设置其实例变量的方法中。
还有什么样的其他解决方案?
I had a straight forward approach of turning Key/Value pairs of an XML excerpt into an NSDictionary when I started a simple iPhone application. The problem is, I need to turn those NSDictionary's instances that once populated my UITableView's into custom classes because they require behavior and additional complexity. The problem here is that now in order for me to instantiate an object and fill its instance variables with key/value pairs from a web service becomes that much more difficult. I can no longer throw it into a method that iterates through the XML and uses KVC to set its instance variables.
What kind of other solution is out there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您仍然可以在自定义类上使用键值编码方法,只要您适当地命名变量,就没有区别。 尽管如此,当我使用 XML 时,我通常最终会测试每个节点名称或创建一个键查找表,因为我正在使用的数据源中的名称不符合键值编码。 如果您可以控制数据源,则可以继续使用
setValue:forKey:
。我建议阅读本指南 关于键值编码(如果您还没有)。 它是 Cocoa 中许多优秀工具的基础。
You can still use key value coding methods on your custom class, as long as you name your variables appropriately there's no difference there. With that being said though, when I'm working with XML I usually end up testing each node name or creating a key lookup table, since the names in the data source I'm working with aren't key value coding compliant. If you have control over the data source though, you could just continue to use
setValue:forKey:
.I'd recommend reading this guide about key value coding if you haven't already. It's fundamental to many great tools in Cocoa.
看看 NSCoding。 您可以使用 NSCoding 协议将对象、属性等全部保存为数据。
一旦您的对象符合 NSCoding 标准,您就可以使用 NSKeyedArchiver 归档整个对象数组。
请注意,如果您有大量对象,这可能会极大地影响应用程序在 iPhone 上加载和保存期间的性能。
Look into NSCoding. You can use the NSCoding protocol to save your object, properties and all, as data.
Once your object is NSCoding compliant, you can just archive the whole array of objects using NSKeyedArchiver.
Please note that if you have a large number of objects, this can dramatically affect the app's performance on the iPhone during load and save.