diff --git a/Sources/CoreModel/InMemoryStore.swift b/Sources/CoreModel/InMemoryStore.swift index ca50792..409105a 100644 --- a/Sources/CoreModel/InMemoryStore.swift +++ b/Sources/CoreModel/InMemoryStore.swift @@ -21,6 +21,11 @@ public actor InMemoryModelStorage { internal let backing: InMemoryStorage + #if !hasFeature(Embedded) + /// Cached view context shared by this store. Only ever accessed from the main actor. + private nonisolated(unsafe) var _viewContext: InMemoryViewContext? + #endif + /// The schema this store validates entities against. public nonisolated var model: Model { backing.model @@ -84,10 +89,16 @@ public extension InMemoryModelStorage { /// A synchronous, main-actor view context backed by the same data as this store. /// - /// Objects inserted or deleted through the store are visible to the returned - /// view context, and vice versa, because both share the same in-memory backing. + /// The same instance is returned on every access. Objects inserted or deleted + /// through the store are visible to the view context, and vice versa, because + /// both share the same in-memory backing. @MainActor var viewContext: InMemoryViewContext { - InMemoryViewContext(backing: backing) + if let existing = _viewContext { + return existing + } + let context = InMemoryViewContext(backing: backing) + _viewContext = context + return context } } #endif diff --git a/Tests/CoreModelTests/InMemoryViewContextTests.swift b/Tests/CoreModelTests/InMemoryViewContextTests.swift index 590f8fd..091d2a1 100644 --- a/Tests/CoreModelTests/InMemoryViewContextTests.swift +++ b/Tests/CoreModelTests/InMemoryViewContextTests.swift @@ -140,6 +140,8 @@ final class InMemoryViewContextTests: XCTestCase { func testSharedDataWithStore() async throws { let store = InMemoryModelStorage(model: Self.model) let context = store.viewContext + // the same cached instance is returned on every access + XCTAssertTrue(context === store.viewContext) // objects inserted through the store are visible to the view context let alice = Person(name: "Alice", age: 30) try await store.insert(alice)