PDA

View Full Version : Struggling with Core Data (part 1)




RonC
May 22, 2011, 05:10 PM
(I'm really new at using CoreData, so if this is super obvious at least be kind when you smack me down ;))

I suspect I'm going to be posting several questions here about Core Data - it seems obtuse to me but I like the abilities is promises to give me.

Here's the first one:

In the code that uses my CoreData model, I use two [related] structures (for several of the entries):
a) [Existence test] Does a Thing A exist with number = X?
b) [Retrieval] Get me the Thing A with number = X.

For example, I have 2 things (Thing A and Thing B) and they're related (Thing A <<-> Thing B). I only want to create a new Thing A or Thing B if they don't already exist (so I use the existence test), and when I create a Thing A and want to associate it to a Thing B. To do that, I use the existence test: if it doesn't exist I create a new one and if it does I use the existing one.

I've implemented this as one method with signature getThingXWithNumber:inContext:. This method sticks all of the core data poop (NSFetchRequest, NSEntityDescription, NSPredicate and the like) into one place for each ThingX. That is a good thing.

I've made this a class method in class ThingA (the one that is generated by Xcode). I'm now beginning to believe this is a mistake as I'm struggling with what to do changes in the data model.

Do you use such code in your apps that use Core Data and if so where do you stick those methods?

UPDATE: I may have self-answered - I've move that code to a new file (RonCoreDataUtils.[hm]) and made it have function instead of message semantics (e.g., thingXwithNumber(number, context)). I'm still curious about what you think is the right way to do this.