问题描述
我已阅读 Marcus S. Zarra 的 核心数据:数据中与 iOS 相关的章节适用于 iOS、OS X 和 iCloud 的存储和管理(第 2 版)带来巨大好处.不过,我想知道一个方面,这本书暗示了一种与我不同的风格.
I have read the iOS-related chapters of Marcus S. Zarra's Core Data: Data Storage and Management for iOS, OS X, and iCloud (2nd edition) to great benefit. I am wondering about one aspect, though, where the book suggests a style that is different from my own.
本书的示例通过使用 KVC(例如 [recipe valueForKey: @"name"]
)访问 NSManagedObject
的属性和关系.关于如何定义属性访问器(例如在 recipe.name
中使用),有(仅)两个简短的解释.这似乎意味着 KVC 明确建议支持属性访问器.
The book's examples access NSManagedObject
s' attributes and relationships by utilizing KVC (e.g. [recipe valueForKey: @"name"]
). There are (only) two brief explanations of how one could go about defining property accessors (e.g. for use in recipe.name
). This seems to imply a clear recommendation of KVC in favor of property accessors.
我通常喜欢属性访问器,例如因为它们可以防止由拼写错误引起的错误(例如 [recipe valueForKey: @"nam"]
)并且因为 Xcode 可以为我生成它们的源代码(Editor
| 创建 NSManagedObject 子类
).
I generally like property accessors, e.g. because they guard against bugs caused by typos (e.g. [recipe valueForKey: @"nam"]
) and because Xcode can generate their source code for me (Editor
| Create NSManagedObject Subclass
).
我的问题是:为什么应该使用 KVC 而不是一般的属性访问器样式有技术原因吗?
My question is this: are there technical reasons for why one should use KVC instead of property-accessor style in general?
推荐答案
KVC 非常有用,书中强调了 KVC 的使用,因为坦率地说,iOS 开发并没有在我看来足够观点.理解 KVC 是 iOS 开发人员工具包中的一个非常有用的工具,不幸的是,它的教学已经搁置了.
KVC is very useful and the book stresses the use of KVC because, quite frankly, iOS development does not stress it enough in my opinion. Understanding KVC is an extremely useful tool in an iOS developer's toolkit and unfortunately the teaching of it has been left by the wayside.
话虽如此,出于您所述的原因,您应该使用属性访问器.它们确实在编译时而不是运行时捕获错误,并且速度要快一点.
Having said that, for the reasons you stated, you should be using property accessors. They do catch errors at compile time rather than run time and are a tiny amount faster.
KVC 在您对集合进行操作时很有用,并且在动态情况下或在您不一定知道正在处理的对象的情况下非常有用.这些是点语法失败的地方.点语法不适用于 id
,在我看来,它是 Objective-C 开发的基石.
KVC is useful when you are doing manipulations on collections and are very useful in dynamic situations or in situations where you don't necessarily know what object you are working against. These are areas where dot syntax fails rather horribly. Dot syntax does not work with id
which, in my opinion, in a corner stone of Objective-C development.
无论如何,没有理由不使用属性访问器,我通常在我的生产代码中使用它们.
In any case, there is no reason not to use property accessors and I generally use them in my production code.
最后一点:我不使用 Xcode 的代码生成.它有足够的缺陷,我建议人们改用 mogenerator.您将获得更好的结果和更易于维护的代码库.
One final note: I do not use Xcode's code generation. It has enough flaws that I recommend people use mogenerator instead. You will have better results and a more maintainable code base.
这篇关于首选属性访问器或 KVC 样式来访问核心数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!