-
Notifications
You must be signed in to change notification settings - Fork 0
/
CoreDataManager.swift
55 lines (46 loc) · 1.86 KB
/
CoreDataManager.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
//
// CoreDataManager.swift
//
// Created by Chris Coffin on 2/27/18.
// Copyright © 2018 Chris Coffin. All rights reserved.
//
import Foundation
import CoreData
class CoreDataManager {
// Private init to prevent clients from creating another instance
private init() {}
// Create shared instance
static let sharedManager = CoreDataManager()
// Create shared reference for managed context
lazy var managedContext: NSManagedObjectContext = {
return CoreDataManager.sharedManager.persistentContainer.viewContext
}()
// Create shared reference for persistent container "testApp"
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "testApp")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// Create shared FRC for TestItems, sorted by "testKey"
lazy var fetchedResultsController: NSFetchedResultsController<TestItems> = {
let fetchRequest = TestItems.createFetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "testKey", ascending: true)]
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedContext, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultsController
}()
// Commit changes made to managed context
func saveContext() {
if managedContext.hasChanges {
do {
try managedContext.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}