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

SwiftData单个模型出现no such table错误及数据丢失问题求助

SwiftData中ModelB数据丢失及"no such table"问题排查

我在应用里定义了两个SwiftData模型,ModelA运行完全正常,不管模拟器重启多少次数据都能持久化;但ModelB时不时会丢失数据,Xcode调试器还会抛出“no such table”错误,我完全搞不懂两个模型的差异在哪里。

相关代码如下:

@Model
final class ModelA: Identifiable {
    @Attribute(.unique) var id: String
    var name: String
    
    init(id: String = UUID().uuidString, name: String) {
        self.id = id
        self.name = name
    }
}
@Model
final class ModelB: Identifiable {
    @Attribute(.unique) var id: String
    var param: String
    
    init(id: String = UUID().uuidString, param: String) {
        self.id = id
        self.param = param
    }
}
@main
struct MyApp: App {
    var sharedModelContainer: ModelContainer = {
        let schema = Schema([
            ModelA.self,
            ModelB.self
        ])
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            return try ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()

    var body: some Scene {
        WindowGroup {
            TabView { /* === views === */ }
       }.modelContainer(sharedModelContainer)
}

更新:暂时没找到根本原因(我怀疑是和视图层级结构相关的数据获取问题),但已经找到临时解决方案——把ModelB改成遵循Identifiable、Codable、Hashable协议的struct。

内容的提问来源于stack exchange,提问作者moonvader

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 22:40:06