MagicalRecord: multiple databases

前端 未结 3 1967
醉梦人生
醉梦人生 2021-02-08 11:36

I have an app that uses MagicalRecord, and I\'m pre-populating the database with a large amount of data that is used for reference. Within that same data model, I have user-defi

3条回答
  •  半阙折子戏
    2021-02-08 12:28

    Keeping data for different Core Data entities in different store files is well supported and fairly straightforward. However, MagicalRecrd doesn't provide any convenience methods for setting up your Core Data stack in this way. You simply have to allocate your stack manually, and tell MagicalRecord to use the NSPersistentStoreCoordinator you create. Here's how I did it in swift:

    import Foundation
    import CoreData
    import MagicalRecord
    
    class CoreDataSetup {
        static func setupAutoMigratingStack(withContentConfigurationName contentConfigurationName: String, userConfirgurationNameName: String) {
            MagicalRecord.cleanUp()
    
            let managedObjectModel = NSManagedObjectModel.MR_defaultManagedObjectModel()
            let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel!)
    
            let contentURL = NSPersistentStore.MR_urlForStoreName(contentConfigurationName + ".sqlite")
            let userURL = NSPersistentStore.MR_urlForStoreName(userConfirgurationNameName + ".sqlite")
            let options = [
                NSMigratePersistentStoresAutomaticallyOption : true,
                NSInferMappingModelAutomaticallyOption: true,
                NSSQLitePragmasOption: ["journal_mode": "DELETE"]
            ]
            do {
                try persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: contentConfigurationName, URL: contentURL, options: options)
                try persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: userConfirgurationNameName, URL: userURL, options: options)
    
                NSPersistentStoreCoordinator.MR_setDefaultStoreCoordinator(persistentStoreCoordinator)
                NSManagedObjectContext.MR_initializeDefaultContextWithCoordinator(persistentStoreCoordinator)
            } catch {
                print("Error adding persistent store to coordinator: \(error) ")
            }
        }
    }
    

    Note that in my code I'm referring to your concept of the "seed" store as "content" and the user-definable store as "user".

    To accomplish the second aspect of your question, configuring the content store to not be backed up, you simply have to play around with the URLs where you store each store, placing the content store in a non-backed up temporary directory, and copying it to that location up launch from your app bundle if it doesn't exist.

提交回复
热议问题