用于访问Core Data属性的首选属性访问器或KVC样式 [英] Prefer property-accessor or KVC style for accessing Core Data properties

查看:102
本文介绍了用于访问Core Data属性的首选属性访问器或KVC样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读了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.

这本书的例子访问 NSManagedObject

The book's examples access NSManagedObjects' 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可以为我生成他们的源代码(编辑器 | 创建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.

这篇关于用于访问Core Data属性的首选属性访问器或KVC样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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