Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...