-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathCoreDataHelper.swift
91 lines (83 loc) · 2.86 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
84
85
86
87
88
89
90
/*
<samplecode>
<abstract>
Extensions that add convenience methods to Core Data.
</abstract>
</samplecode>
*/
import CoreData
import CloudKit
extension NSPersistentStore {
func contains(manageObject: NSManagedObject) -> Bool {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: manageObject.entity.name!)
fetchRequest.predicate = NSPredicate(format: "self == %@", manageObject)
fetchRequest.affectedStores = [self]
if let context = manageObject.managedObjectContext,
let result = try? context.count(for: fetchRequest), result > 0 {
return true
}
return false
}
}
extension NSManagedObject {
var persistentStore: NSPersistentStore? {
let persistenceController = PersistenceController.shared
if persistenceController.sharedPersistentStore.contains(manageObject: self) {
return persistenceController.sharedPersistentStore
} else if persistenceController.privatePersistentStore.contains(manageObject: self) {
return persistenceController.privatePersistentStore
}
return nil
}
}
extension NSManagedObjectContext {
/**
Contextual information for handling error that happens when saving a managed object context.
*/
enum ContextualInfoForSaving: String {
case addPhoto, deletePhoto
case toggleTagging, deleteTag, addTag
case addRating, deleteRating
case sheetOnDismiss
case deduplicateAndWait
}
/**
Save a context and handle the save error. This sample simply prints the error message. Real apps should
consider comprehensive error handling based on the contextual information.
*/
func save(with contextualInfo: ContextualInfoForSaving) {
if hasChanges {
do {
try save()
} catch {
print("\(#function): Failed to save Core Data context for \(contextualInfo.rawValue): \(error)")
}
}
}
}
/**
A convenience method for creating background contexts that specify the app as their transaction author.
*/
extension NSPersistentCloudKitContainer {
func newTaskContext() -> NSManagedObjectContext {
let context = newBackgroundContext()
context.transactionAuthor = TransactionAuthor.app
return context
}
/**
Fetch and return shares in the persistent stores.
*/
func fetchShares(in persistentStores: [NSPersistentStore]) throws -> [CKShare] {
var results = [CKShare]()
for persistentStore in persistentStores {
do {
let shares = try fetchShares(in: persistentStore)
results += shares
} catch let error {
print("Failed to fetch shares in \(persistentStore).")
throw error
}
}
return results
}
}