-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCoreDataHelper.swift
83 lines (70 loc) · 3.06 KB
/
CoreDataHelper.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// CoreDataHelper.swift
// My_Devoxx
//
// Created by Maxime on 16/03/16.
// Copyright © 2016 maximedavid. All rights reserved.
//
import Foundation
import CoreData
import UIKit
class CoreDataHelper: NSObject{
let mainManager: MainManager!
override init(){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
self.mainManager = appDelegate.mainManager
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.contextDidSaveContext(_:)), name: NSManagedObjectContextDidSaveNotification, object: nil)
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
lazy var mainThreadContext: NSManagedObjectContext = {
let coordinator = self.mainManager.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
lazy var backgroundThreadContext: NSManagedObjectContext? = {
let coordinator = self.mainManager.persistentStoreCoordinator
var backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
backgroundContext.persistentStoreCoordinator = coordinator
return backgroundContext
}()
func saveContext (context: NSManagedObjectContext) {
var error: NSError? = nil
if context.hasChanges {
do {
try context.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
func saveContext () {
self.saveContext( self.backgroundThreadContext! )
}
func contextDidSaveContext(notification: NSNotification) {
let sender = notification.object as! NSManagedObjectContext
if sender === self.mainThreadContext {
self.backgroundThreadContext!.performBlock {
self.backgroundThreadContext!.mergeChangesFromContextDidSaveNotification(notification)
}
} else if sender === self.backgroundThreadContext {
self.mainThreadContext.performBlock {
self.mainThreadContext.mergeChangesFromContextDidSaveNotification(notification)
}
} else {
self.backgroundThreadContext!.performBlock {
self.backgroundThreadContext!.mergeChangesFromContextDidSaveNotification(notification)
}
self.mainThreadContext.performBlock {
self.mainThreadContext.mergeChangesFromContextDidSaveNotification(notification)
}
}
}
}