12.3 C
New York
Monday, November 4, 2024

The best way to make CoreData Supervisor with multi accounts?


My iOS app can change account.
SQLite file is saved to [account]_dbfile.sqlite.
If I logged in ABC named account, name CoreDataManager.shared.setup("ABC") and fetch, save blahblah…
Then, if I modify Account DEF named, name CoreDataManager.shared.resetCoreDataObjects() -> CoreDataManager.shared.setup("DEF") and fetch, save blahblah…

That is my code.
I do not know that is appropriate code.

class CoreDataManager: NSObject {
    static let shared = CoreDataManager()
    personal(set) var isLoggedin: Bool = false
    
    personal lazy var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(identify: "TestAppModel")
        container.loadPersistentStores { _, error in }
        return container
    }()
    
    personal var moc: NSManagedObjectContext {
        if Thread.isMainThread {
            return persistentContainer.viewContext
        } else {
            return privateContext
        }
    }
    
    personal lazy var privateContext: NSManagedObjectContext = {
        let privateManagedContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        privateManagedContext.mum or dad = persistentContainer.viewContext
        return privateManagedContext
    }()
    
    func setup(_ userId: String) -> Bool {
        moc.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
        
        guard let path = FileManager.databasePath(userId: userId) else {        // ex) "~/[userId]_dbfile.sqlite"
            isLoggedin = false
            return isLoggedin
        }
        
        for persistentStore in persistentContainer.persistentStoreCoordinator.persistentStores {
            if persistentStore.url?.lastPathComponent == path.lastDepthName() {
                isLoggedin = true
                print("Already added PersistentStore = (String(describing: persistentStore.url?.relativePath))")
                
                return true
            }
        }
        
        let choices: [String: Any] = [NSMigratePersistentStoresAutomaticallyOption: true,
                                            NSInferMappingModelAutomaticallyOption: true,
                                                NSPersistentStoreFileProtectionKey: FileProtectionType.complete]
        
        do {
            _ = attempt persistentContainer.persistentStoreCoordinator.addPersistentStore(sort: .sqlite, at: URL(fileURLWithPath: path), choices: choices)
        } catch {
            isLoggedin = false
            return isLoggedin
        }
        
        isLoggedin = true
        return isLoggedin
    }
    
    func resetCoreDataObjects() {
        moc.performAndWait {
            for retailer in persistentContainer.persistentStoreCoordinator.persistentStores {
                attempt? persistentContainer.persistentStoreCoordinator.take away(retailer)
            }
        }
    }
}

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles