You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SceneDelegate中正确初始化SwiftData的ModelContainer?

在UIKit项目的SceneDelegate中初始化SwiftData的ModelContainer

要在SceneDelegate中正确初始化SwiftData的ModelContainer,你需要指定数据模型类型并处理初始化时的异常,具体方案如下:

修改后的SceneDelegate代码

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?
    
    var modelContainer: ModelContainer!
    

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // 初始化ModelContainer
        do {
            // 替换成你的实际数据模型类型,比如[Customer.self],多模型可添加到数组中
            modelContainer = try ModelContainer(for: [Customer.self])
        } catch {
            // 处理初始化失败的情况,比如打印错误或执行降级逻辑
            fatalError("ModelContainer初始化失败: \(error.localizedDescription)")
        }
        
        guard let windowScene = (scene as? UIWindowScene) else { return }
        let window = UIWindow(windowScene: windowScene)
        let customerListVC = CustomerListVC(viewModel: CustomerListViewModel(customerService: CustomerService(context: modelContainer.mainContext)))
        let navigationController = UINavigationController(rootViewController: customerListVC)
        window.rootViewController = navigationController
    

        self.window = window
        window.makeKeyAndVisible()
     }
}

关键说明

  • 指定数据模型:初始化ModelContainer时必须传入你的数据模型类型数组,SwiftData需要通过这些类型识别要管理的数据结构。
  • 异常处理:ModelContainer的初始化方法会抛出错误(比如模型定义非法、存储权限不足等),必须用do-catch块捕获处理,避免程序崩溃。
  • 获取主上下文:初始化完成后,通过modelContainer.mainContext可以获取默认的主上下文,直接传给你的CustomerService即可。

内容的提问来源于stack exchange,提问作者Zin Win Htet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 00:47:36