Aar*_*her 9 swift-data xcode15
我想创建一个类来定期处理一些数据。我没有使用过CoreData。在 SwiftUI 视图之外,如何获取模型容器和上下文以便检索和添加对象?WWDC 视频中显示的代码let context = self.newSwiftContext(from: Trip.self)并不是不言自明的。
创建容器后
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,例如单例、在应用程序生命周期中保留的服务等。
| 归档时间: |
|
| 查看次数: |
2350 次 |
| 最近记录: |