I've created a database of objects using Core Data. I want my app to have the functionality to support multiple users. Each user should be able to see the list of objects stored in the database, and can then select the desired objects that they want to use within their account in the app.
What's the best way to implement this? I want to create a separate persistent store for each user. Shared objects, like the default main list of objects that the user chooses from, should be part of a 'common' persistent store, from which the objects in each user's persistent store will point to, so that I'm not creating a bunch of duplicate objects.
On top of that, each object in the main list has children managed objects. The children can be modified by each user and so they should be unique to each user's persistent store.
Any suggestions for best practices? I'm fairly new to Core Data.
Note: Only 1 user can be logged in at a time.
Thanks so much!
You can add several stores to the same persistent store coordinator, and it should all just work. Some things to know include:
If you have more than one store that contain the same entity (i.e. type of object), you'll have to use NSManagedObjectContext's
-assignObject:toPersistentStore:method to tell the context which store to use for each new object that you add.
Any particular object can exist only in one persistent store. For example, if you have several Person objects like Tom, Dick, and Harriet, all three can exist in a single store, or they can be divided among multiple stores, but a given object such as Tom can exist only in a single store.
Core Data doesn't let you create relationships between objects in different stores. If Tom and Dick are brothers, and you want to record that relationship in your model, they should be assigned to the same store. It's possible to use a fetched property instead of a relationship, but that's not quite as simple as a relationship.
So, if you go down the separate stores path, the common store could contain a set of 'prototype' objects for the user to pick from. When the user picks an object, you'd copy that object into the user's own store, and work with that new object from that point on. That way, you could use relationships to keep track of each object's children, and the changes to the children would remain unique to each user. The alternative would be to keep the main objects in the common store and use fetched relationships to relate them to the child objects in the user's store, but that seems more complicated.