diff --git a/Sources/HandySwiftUI/Extensions/PersistentModelExt.swift b/Sources/HandySwiftUI/Extensions/PersistentModelExt.swift index 18bb182..df4da84 100644 --- a/Sources/HandySwiftUI/Extensions/PersistentModelExt.swift +++ b/Sources/HandySwiftUI/Extensions/PersistentModelExt.swift @@ -3,18 +3,18 @@ @available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *) extension PersistentModel { - /// Returns whether this model instance is currently managed by a ModelContext. + /// Returns whether this model instance is currently managed by a `ModelContext`. /// - /// Use this property to determine if a model instance has ever been inserted into - /// a ModelContext (i.e., exists in the database) or if it's just an in-memory instance - /// that hasn't been saved yet. + /// Use this property to determine if a model instance has been inserted into a `ModelContext` or if it's just an in-memory + /// instance that was never inserted. Inserting is enough for this to be `true`: the model might not be saved to the store yet. + /// To check whether it was saved, use `persistentModelID.isTemporary` (iOS 27, macOS 27, tvOS 27, watchOS 27, visionOS 27). /// /// Example: /// ```swift /// let task = Task(title: "New Task") /// print(task.isPersisted) // false /// - /// try modelContext.insert(task) + /// modelContext.insert(task) /// print(task.isPersisted) // true /// ``` public var isPersisted: Bool { diff --git a/Tests/HandySwiftUITests/PersistentModelExtTests.swift b/Tests/HandySwiftUITests/PersistentModelExtTests.swift new file mode 100644 index 0000000..15eb2ed --- /dev/null +++ b/Tests/HandySwiftUITests/PersistentModelExtTests.swift @@ -0,0 +1,27 @@ +import SwiftData +import Testing + +@testable import HandySwiftUI + +@Model +final class TestItem { + var title: String + + init(title: String) { + self.title = title + } +} + +@MainActor +struct PersistentModelExtTests { + @Test + func insertingIsEnoughWithoutSaving() throws { + let container = try ModelContainer(for: TestItem.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true)) + let item = TestItem(title: "New Item") + #expect(!item.isPersisted) + + container.mainContext.insert(item) + #expect(item.isPersisted) + #expect(container.mainContext.hasChanges, "not saved yet") + } +}