2 // ManagedObjectContextGenerator.swift
5 // Created by Hori,Masaki on 2017/03/21.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
11 enum CoreDataError: Error {
13 case applicationDirectoryIsFile
14 case couldNotCreateModel
15 case couldNotCreateCoordinator(String)
18 func remove(name: String) {
22 .map { ApplicationDirecrories.support.appendingPathComponent($0) }
23 .forEach { removeDataFile(at: $0) }
26 func genarate(_ config: CoreDataConfiguration) throws -> (model: NSManagedObjectModel, coordinator: NSPersistentStoreCoordinator, moc: NSManagedObjectContext) {
30 let model = try createModel(config)
31 let coordinator = try getCoordinator(config, model)
32 let moc = createContext(coordinator)
34 return (model: model, coordinator: coordinator, moc: moc)
42 private func removeDataFile(at url: URL) {
46 try FileManager.default.removeItem(at: url)
50 print("Could not remove file for URL (\(url))")
54 // MARK: - NSManagedObjectContext and ...
55 private func createModel(_ config: CoreDataConfiguration) throws -> NSManagedObjectModel {
57 guard let modelURL = Bundle.main.url(forResource: config.modelName, withExtension: "momd"),
58 let model = NSManagedObjectModel(contentsOf: modelURL)
60 throw CoreDataError.couldNotCreateModel
65 private func getCoordinator(_ config: CoreDataConfiguration, _ model: NSManagedObjectModel) throws -> NSPersistentStoreCoordinator {
69 return try createCoordinator(config, model)
73 let nserror = error as NSError
74 // Data Modelが更新されていたらストアファイルを削除してもう一度
75 if nserror.domain == NSCocoaErrorDomain,
76 (nserror.code == 134130 || nserror.code == 134110),
79 remove(name: config.fileName)
83 return try createCoordinator(config, model)
87 print("Fail crrate NSPersistentStoreCoordinator twice.")
95 private func createCoordinator(_ config: CoreDataConfiguration, _ model: NSManagedObjectModel) throws -> NSPersistentStoreCoordinator {
97 if !checkDirectory(ApplicationDirecrories.support) {
99 let failureReason = "Can not use directory \(ApplicationDirecrories.support.path)"
101 throw CoreDataError.couldNotCreateCoordinator(failureReason)
104 let coordinator: NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
105 let url = ApplicationDirecrories.support.appendingPathComponent(config.fileName)
109 try coordinator.addPersistentStore(ofType: config.type,
110 configurationName: nil,
112 options: config.options)
122 private func createContext(_ coordinator: NSPersistentStoreCoordinator) -> NSManagedObjectContext {
124 let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
125 moc.persistentStoreCoordinator = coordinator
126 moc.undoManager = nil