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

1

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.

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?

Landed answered 6/3, 2015 at 12:37 Comment(2)
This question covers similar ground, albeit without the CoreData focus.Sophiasophie
Tx: your quote from Apple docs re performance impact (in answer to linked question) was helpful.Landed
M
3

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.

Motet answered 6/3, 2015 at 16:17 Comment(1)
Tx. I have posted a second follow-up question. That should be it. If you are interested: I also have three (short-as-a-comment) recommendations for a possible 3rd edition of the book.Landed

© 2022 - 2024 — McMap. All rights reserved.