OSDN Git Service

定数をインライン化
[kcd/KCD.git] / KCD / CoreDataCore.swift
1 //
2 //  CoreDataManager.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/02/05.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11 struct CoreDataConfiguration {
12     
13     let modelName: String
14     let fileName: String
15     let options: [AnyHashable: Any]
16     let type: String
17     
18     // try remake data file, if model file modified.
19     let tryRemake: Bool
20     
21     private static let defaultOptions: [AnyHashable: Any] = [
22         NSMigratePersistentStoresAutomaticallyOption: true,
23         NSInferMappingModelAutomaticallyOption: true
24     ]
25     
26     init(_ modelName: String,
27          fileName: String? = nil,
28          options: [AnyHashable: Any] = defaultOptions,
29          type: String = NSSQLiteStoreType,
30          tryRemake: Bool = false) {
31         
32         self.modelName = modelName
33         self.fileName = fileName ?? "\(modelName).storedata"
34         self.options = options
35         self.type = type
36         self.tryRemake = tryRemake
37     }
38 }
39
40 struct CoreDataCore {
41     
42     let config: CoreDataConfiguration
43     let parentContext: NSManagedObjectContext
44     private let model: NSManagedObjectModel
45     private let coordinator: NSPersistentStoreCoordinator
46     
47     init(_ config: CoreDataConfiguration) {
48         
49         self.config = config
50         
51         do {
52             
53             (model, coordinator, parentContext) = try MOCGenerator(config).genarate()
54             
55         } catch {
56             
57             NSApplication.shared.presentError(error)
58             fatalError("CoreDataCore: can not initialize. \(error)")
59         }
60     }
61     
62     func editorContext() -> NSManagedObjectContext {
63         
64         let moc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
65         moc.parent = parentContext
66         moc.undoManager = nil
67         
68         return moc
69     }
70 }