So I’m using Core Data in an existing iPhone app, and I’ve set up two entities: Person and Item. The root view of my app’s navigation (currently) shows a list of people, and you drill down from there to items. In short, the hierarchy looks like this:
Person -> Item
I want to add a new entity above Person in the hierarchy, called List:
List -> Person -> Item
Additionally, I want the user’s first List to be created for them on startup, and for any People the user’s already added to be assigned to that list.
I’m familiar with Core Data’s lightweight migration & versioning feature, so I think I know how to add the new entity and relationship, but I’m not sure how to:
-
Create a List record on app start if they’ve never had the Lists feature before
-
Set all existing People records to belong to that new list.
One quick and dirty way would be to add some code to my app delegate’s applicationDidFinishLaunching method that performs the migration by (1) checking to see if there are any Lists, (2) if not, creating the default one, (3) fetching all existing People from my data store, (4) setting each Person’s list attribute to the newly created default list, and finally (5) saving those changes.
My question is: is there any faster or easier way to do all of that?
That’s pretty much what you’d want to do. Use an
NSFetchRequestto see if anyListss exist. If not, create one. Then do another request to get all thePersons. Here, instead of assigning thelistproperty of eachPerson, I’d create anNSSetcontaining all yourPersons and assign that to theList‘speopleproperty. You did create an inverse property, right?This is actually a pretty lightweight operation, all tolled, so I wouldn’t worry too much about performance. Unless you’ve got hundreds or thousands of
Personobjects, your user will probably won’t even notice.