|
7 | 7 |
|
8 | 8 | #if canImport(CoreData) |
9 | 9 | import Foundation |
| 10 | +import Combine |
10 | 11 | import CoreData |
11 | 12 | import CoreModel |
12 | 13 |
|
13 | | -extension NSManagedObjectContext: ModelStorage, ViewContext { |
| 14 | +extension NSManagedObjectContext: ModelStorage { |
14 | 15 |
|
15 | 16 | public func fetch(_ entity: EntityName, for id: ObjectID) throws -> ModelData? { |
16 | 17 | try self.find(entity, for: id) |
@@ -58,6 +59,41 @@ extension NSManagedObjectContext: ModelStorage, ViewContext { |
58 | 59 | } |
59 | 60 | } |
60 | 61 |
|
| 62 | +@MainActor |
| 63 | +public final class ManagedObjectViewContext: ViewContext, ObservableObject { |
| 64 | + |
| 65 | + internal let context: NSManagedObjectContext |
| 66 | + |
| 67 | + public init(context: NSManagedObjectContext) { |
| 68 | + self.context = context |
| 69 | + assert(context.concurrencyType == .mainQueueConcurrencyType) |
| 70 | + } |
| 71 | + |
| 72 | + public init(persistentContainer: NSPersistentContainer) { |
| 73 | + self.context = persistentContainer.viewContext |
| 74 | + } |
| 75 | + |
| 76 | + /// Fetch managed object. |
| 77 | + public func fetch(_ entity: EntityName, for id: ObjectID) throws -> ModelData? { |
| 78 | + try context.fetch(entity, for: id) |
| 79 | + } |
| 80 | + |
| 81 | + /// Fetch managed objects. |
| 82 | + public func fetch(_ fetchRequest: FetchRequest) throws -> [ModelData] { |
| 83 | + try context.fetch(fetchRequest) |
| 84 | + } |
| 85 | + |
| 86 | + /// Fetch managed objects IDs. |
| 87 | + public func fetchID(_ fetchRequest: FetchRequest) throws -> [ObjectID] { |
| 88 | + try context.fetchID(fetchRequest) |
| 89 | + } |
| 90 | + |
| 91 | + /// Fetch and return result count. |
| 92 | + public func count(_ fetchRequest: FetchRequest) throws -> UInt { |
| 93 | + try context.count(fetchRequest) |
| 94 | + } |
| 95 | +} |
| 96 | + |
61 | 97 | internal extension NSManagedObjectContext { |
62 | 98 |
|
63 | 99 | func fetchObjects(_ fetchRequest: FetchRequest) throws -> [NSManagedObject] { |
|
0 commit comments