在 SwiftUI 之外使用 SwiftData

Aar*_*her 9 swift-data xcode15

我想创建一个类来定期处理一些数据。我没有使用过CoreData。在 SwiftUI 视图之外,如何获取模型容器和上下文以便检索和添加对象?WWDC 视频中显示的代码let context = self.newSwiftContext(from: Trip.self)并不是不言自明的。

lor*_*sum 4

创建容器后

let configuration = ModelConfiguration(isStoredInMemoryOnly: true, allowsSave: false)


let container = try ModelContainer(
    for: Trip.self, Accommodation.self, 
    configurations: configuration
)
Run Code Online (Sandbox Code Playgroud)

您可以直接从容器访问上下文。

let context = container.mainContext
Run Code Online (Sandbox Code Playgroud)

https://developer.apple.com/documentation/swiftdata/preserving-your-apps-model-data-across-launches

我建议确保容器存储在稳定的地方UIApplicationDelegate,例如单例、在应用程序生命周期中保留的服务等。

  • 一件事是,“container.mainContext”是异步的,因此要在非异步代码中获取上下文,您应该执行“let context = ModelContext(container)” (2认同)