Prefer property-accessor or KVC style for accessing Core Data properties

和自甴很熟 提交于 2019-11-27 08:31:06

问题


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.

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.

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).

My question is this: are there technical reasons for why one should use KVC instead of property-accessor style in general?


回答1:


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 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.

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.



来源:https://stackoverflow.com/questions/28898966/prefer-property-accessor-or-kvc-style-for-accessing-core-data-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!