@@ -44,6 +44,21 @@ public extension ModelStorage {
4444 }
4545}
4646
47+ public protocol ViewContext {
48+
49+ /// Fetch managed object.
50+ func fetch( _ entity: EntityName , for id: ObjectID ) throws -> ModelData ?
51+
52+ /// Fetch managed objects.
53+ func fetch( _ fetchRequest: FetchRequest ) throws -> [ ModelData ]
54+
55+ /// Fetch managed objects IDs.
56+ func fetchID( _ fetchRequest: FetchRequest ) throws -> [ ObjectID ]
57+
58+ /// Fetch and return result count.
59+ func count( _ fetchRequest: FetchRequest ) throws -> UInt
60+ }
61+
4762// MARK: - ModelData
4863
4964/// CoreModel Object Instance
@@ -132,3 +147,52 @@ public extension ModelStorage {
132147 try await delete ( T . entityName, for: objectID)
133148 }
134149}
150+
151+ public extension ViewContext {
152+
153+ /// Fetch managed object.
154+ func fetch< T> ( _ entity: T . Type , for id: T . ID ) throws -> T ? where T: Entity {
155+ let objectID = ObjectID ( rawValue: id. description)
156+ guard let model = try fetch ( T . entityName, for: objectID) else {
157+ return nil
158+ }
159+ return try T . init ( from: model)
160+ }
161+
162+ /// Fetch managed objects.
163+ func fetch< T> (
164+ _ entity: T . Type ,
165+ sortDescriptors: [ FetchRequest . SortDescriptor ] = [ ] ,
166+ predicate: FetchRequest . Predicate ? = nil ,
167+ fetchLimit: Int = 0 ,
168+ fetchOffset: Int = 0
169+ ) throws -> [ T ] where T: Entity {
170+ let fetchRequest = FetchRequest (
171+ entity: T . entityName,
172+ sortDescriptors: sortDescriptors,
173+ predicate: predicate,
174+ fetchLimit: fetchLimit,
175+ fetchOffset: fetchOffset
176+ )
177+ return try fetch ( fetchRequest)
178+ . map { try T . init ( from: $0) }
179+ }
180+
181+ /// Fetch and return result count.
182+ func count< T> (
183+ _ entity: T . Type ,
184+ sortDescriptors: [ FetchRequest . SortDescriptor ] = [ ] ,
185+ predicate: FetchRequest . Predicate ? = nil ,
186+ fetchLimit: Int = 0 ,
187+ fetchOffset: Int = 0
188+ ) throws -> UInt where T: Entity {
189+ let fetchRequest = FetchRequest (
190+ entity: T . entityName,
191+ sortDescriptors: sortDescriptors,
192+ predicate: predicate,
193+ fetchLimit: fetchLimit,
194+ fetchOffset: fetchOffset
195+ )
196+ return try count ( fetchRequest)
197+ }
198+ }
0 commit comments