I have only one database model schema in my app, so IMHO, NSManagedObjectModel and NSPersistentStoreCoordinator objects might reside in main app delegate class for accessing from other parts of the app. However, I would like to have different NSManagedObjectContexts objects for various parts of my app because I will use multithreading.
From my personal database experience, I assume NSManagedObjectContext is somehow similar to the concept of database transaction. So, it's logical to have separate context objects for various multi-threaded parts of my app in order to avoid committing unwanted changes from one app part to another. When creating new project with enabled for core data, Xcode creates three essential methods in main app delegate
- (NSManagedObjectModel *)managedObjectModel{
// reads your database model file and defined entities from defined DataSchema.xcdatamodeld file
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{
// uses already read database model and initializes defined sqlite database file and returns a persistent store coordinator - a pointer to the database
}
- (NSManagedObjectContext *)managedObjectContext{
// opens a connection (and transaction) to the database.
}
So, the question would be, is it reasonable to leave persistentStoreCoordinator and managedObjectModel methods in main app delegate (and access them through the app), but to move managedObjectContext method to those classes that need private data handling?