NSManagedObjectContext.swift 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. //
  2. // NSManagedObjectContext.swift
  3. // LoopKit
  4. //
  5. // Copyright © 2018 LoopKit Authors. All rights reserved.
  6. //
  7. import Foundation
  8. import CoreData
  9. extension NSManagedObjectContext {
  10. /// Deletes all saved objects matching the specified type and predicate from the context's persistent store
  11. ///
  12. /// - Parameters:
  13. /// - type: The object type to delete
  14. /// - predicate: The predicate to match
  15. /// - Returns: The number of deleted objects
  16. /// - Throws: NSBatchDeleteRequest execution errors
  17. public func purgeObjects<T: NSManagedObject>(of type: T.Type, matching predicate: NSPredicate? = nil) throws -> Int {
  18. let fetchRequest: NSFetchRequest<NSFetchRequestResult> = T.fetchRequest()
  19. fetchRequest.predicate = predicate
  20. let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
  21. deleteRequest.resultType = .resultTypeObjectIDs
  22. let result = try execute(deleteRequest)
  23. guard let deleteResult = result as? NSBatchDeleteResult,
  24. let objectIDs = deleteResult.result as? [NSManagedObjectID]
  25. else {
  26. return 0
  27. }
  28. if objectIDs.count > 0 {
  29. let changes = [NSDeletedObjectsKey: objectIDs]
  30. NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [self])
  31. self.refreshAllObjects()
  32. }
  33. return objectIDs.count
  34. }
  35. /// Deletes all saved objects returned from the specified fetch request
  36. ///
  37. /// - Parameters:
  38. /// - fetchRequest: The fetch request performed to determine objects to subsequently delete
  39. /// - Returns: The number of deleted objects
  40. /// - Throws: Any core data error during fetch or delete
  41. public func deleteObjects<T>(matching fetchRequest: NSFetchRequest<T>) throws -> Int where T: NSManagedObject {
  42. let objects = try fetch(fetchRequest)
  43. objects.forEach { delete($0) }
  44. if hasChanges {
  45. try save()
  46. }
  47. return objects.count
  48. }
  49. }
  50. extension NSManagedObjectContext {
  51. /// Returns the anchor key. The anchor key is a monotonically increasing integer
  52. /// that auto-increments on every call to this property. The global value is stored in the first
  53. /// peristent store associated with this context.
  54. ///
  55. /// - Return: The next anchor key for the persistent store associated with this context.
  56. public var anchorKey: Int64? { modificationCounter }
  57. /// Returns the modification counter. The modification counter is a monotonically increasing integer
  58. /// that auto-increments on every call to this property. The global value is stored in the first
  59. /// peristent store associated with this context.
  60. ///
  61. /// - Return: The next modification counter for the persistent store associated with this context.
  62. public var modificationCounter: Int64? {
  63. get {
  64. guard let persistentStoreCoordinator = persistentStoreCoordinator,
  65. let persistentStore = persistentStoreCoordinator.persistentStores.first
  66. else {
  67. return nil
  68. }
  69. return NSManagedObjectContext.modificationCounterLock.withLock {
  70. var metadata = persistentStoreCoordinator.metadata(for: persistentStore)
  71. var modificationCounter: Int64
  72. if let previousModificationCounter = metadata[NSManagedObjectContext.modificationCounterMetadataKey] as? Int64 {
  73. modificationCounter = previousModificationCounter + 1
  74. } else {
  75. modificationCounter = 1
  76. }
  77. metadata[NSManagedObjectContext.modificationCounterMetadataKey] = modificationCounter
  78. persistentStoreCoordinator.setMetadata(metadata, for: persistentStore)
  79. return modificationCounter
  80. }
  81. }
  82. }
  83. private static let modificationCounterMetadataKey = "modificationCounter"
  84. private static let modificationCounterLock = UnfairLock()
  85. }