Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions Sources/CoreModel/InMemoryStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions Tests/CoreModelTests/InMemoryViewContextTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading