NSDictionary 与自定义对象
问题很简单:当我创建一个新的 API 或服务类时,我应该为正在传递的对象创建一个自定义类,还是应该坚持使用仅将数据保存在中的 NSDictionary
键值样式格式。
显然,各有利弊,但你们认为使用其中一种的门槛在哪里?
NSDictionary
:
+
无依赖项+
非常灵活+
常用+
对 NSCoding
的内置支持-
结构未定义 ->运行时错误
自定义对象:
+
已定义结构+
属性样式访问器:myObject.someProperty
-
可以产生 rel。嵌套对象的大量类
更新:包含来自 jbat100 的备注
The question is quite simple: When I create a new API or Service Class should I create a custom class for the objects that are being passed around or should I just stick to an NSDictionary
which simply holds the data in a key-value-style format.
Obviously there are pros and cons but where do you guys think is the threshold of using one over the other?
NSDictionary
:
+
No dependencies+
Very Flexible+
Commonly used+
Build-in support for NSCoding
-
Structure not defined -> Runtime errors
A custom Object:
+
Structure defined+
Property-style accessors: myObject.someProperty
-
Can result in a rel. big number of classes for nested objects
Update: Included remarks from jbat100
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我通常有一组领域模型,它更适合 iPhone 开发的 MVC 方法。拥有特定的对象还可以使您更轻松地强制执行类型安全,并且从长远来看还可以降低复杂性。如果你有包含 NSArray 和更多 NSDictionaries 等的 NSDictionaries 来表示你的对象图,它很快就会变得难以管理。
I usually have a set of domain models, which fit better with the MVC approach of iPhone development. Having specific objects also enables you to enforce type-safety a lot easier and also reduces complexity in the long run. If you have NSDictionaries containing NSArrays and more NSDictionaries etc etc to represent your object graph, it can very quickly become unmanageable.
这实际上取决于您期望数据模型改变的程度。一旦您拥有基于自定义类的数据模型,处理更改可能会很棘手,特别是当您拥有不同版本模型的存档(NSCoding 内容)(在应用程序的已发布版本中)时,您必须非常小心,以确保向后兼容性和避免令人讨厌的运行时意外。在这方面,正如您所说,基于 NSDictionary 的模型更加灵活。然而,它们不允许自定义类所做的所有自定义检查和行为。此外,自定义类使数据模型对于不熟悉代码的编码人员来说更加明确,根据我的经验,开发人员在处理基于 NSDictionary 的模型时常常会变得马虎(尤其是在没有经验的情况下),这很快就会导致难以理解的混乱,所以如果你继续下去路线、记录并遵守纪律!
It really depends how much you expect your data model to change. Dealing with changes once you have a custom class based data model can be tricky especially when you have archives (NSCoding stuff) with different versions of the model (in already shipped versions of your app), you must be very careful to ensure backwards compatibility and avoid nasty run time surprises. In that respect NSDictionary based models are, as you say more flexible. However they do not allow all the customized checks and behaviour that custom classes do. Also custom classes make the data model more explicit for coders unfamiliar with the code, from my experience, developers often get sloppy (especially when inexperienced) when dealing with NSDictionary based models which can quickly result in an incomprehensible mess, so if you go down that route, document well and be disciplined!
如果您需要只读访问并且不需要方法,您可以执行以下操作:
并使用它:
If you need readonly access and do not need methods, you can do following:
And use it: