-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataController.swift
57 lines (45 loc) · 2 KB
/
DataController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//
// DataController.swift
// Harvey
//
// Created by Sean Hart on 9/2/17.
// Copyright © 2017 TangoJ Labs, LLC. All rights reserved.
//
import UIKit
import CoreData
class DataController: NSObject
{
var managedObjectContext: NSManagedObjectContext
var psc: NSPersistentStoreCoordinator
override init()
{
// This resource is the same name as your xcdatamodeld contained in your project.
guard let modelURL = Bundle.main.url(forResource: "Harvey", withExtension:"momd") else
{
fatalError("Error loading model from bundle")
}
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
guard let mom = NSManagedObjectModel(contentsOf: modelURL) else
{
fatalError("Error initializing mom from: \(modelURL)")
}
psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
self.managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
self.managedObjectContext.persistentStoreCoordinator = psc
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docURL = urls[urls.endIndex-1]
/* The directory the application uses to store the Core Data store file.
This code uses a file named "DataModel.sqlite" in the application's documents directory.
*/
let storeURL = docURL.appendingPathComponent("DataModel.sqlite")
// Try to migrate the data store, if it fails (the store model changed, reset the store)
do
{
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true])
}
catch
{
fatalError("Error migrating store: \(error)")
}
}
}