-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathCoreDataHelper+BatchDelete.swift
78 lines (66 loc) · 3.15 KB
/
CoreDataHelper+BatchDelete.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
//
// CoreDataHelper+BatchDelete.swift
// OpenGpxTracker
//
// Created by Vincent on 1/8/20.
//
import CoreData
extension CoreDataHelper {
@available(iOS 10.0, *)
func modernBatchDelete<T: NSManagedObject>(of type: T.Type) {
let privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateManagedObjectContext.parent = appDelegate.managedObjectContext
privateManagedObjectContext.perform {
do {
let name = "\(T.self)" // Generic name of the object is the entityName
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: name)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
// execute delete request.
try privateManagedObjectContext.execute(deleteRequest)
try privateManagedObjectContext.save()
self.appDelegate.managedObjectContext.performAndWait {
do {
// Saves the changes from the child to the main context to be applied properly
try self.appDelegate.managedObjectContext.save()
} catch {
print("Failure to save context after delete: \(error)")
}
}
} catch {
print("Failed to delete all from core data, error: \(error)")
}
}
}
func legacyBatchDelete<T: NSManagedObject>(of type: T.Type) {
let privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateManagedObjectContext.parent = appDelegate.managedObjectContext
// Creates a fetch request
let fetchRequest = NSFetchRequest<T>(entityName: "\(T.self)")
fetchRequest.includesPropertyValues = false
let asynchronousWaypointFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { asynchronousFetchResult in
// Retrieves an array of points from Core Data
guard let results = asynchronousFetchResult.finalResult else { return }
for result in results {
privateManagedObjectContext.delete(result)
}
do {
try privateManagedObjectContext.save()
self.appDelegate.managedObjectContext.performAndWait {
do {
// Saves the changes from the child to the main context to be applied properly
try self.appDelegate.managedObjectContext.save()
} catch {
print("Failure to save context: \(error)")
}
}
} catch {
print("Failure to save context at child context: \(error)")
}
}
do {
try privateManagedObjectContext.execute(asynchronousWaypointFetchRequest)
} catch let error {
print("NSAsynchronousFetchRequest (while deleting \(T.self) error: \(error)")
}
}
}