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

SwiftUI中为Realm对象添加新属性时触发Schema版本错误求助

SwiftUI中Realm添加属性时遇到Schema版本错误的解决方法

遇到的错误信息

Thread 1: Fatal error: 'try!' expression unexpectedly raised an error:
Error Domain=io.realm Code=1 "Provided schema version 0 is less than last set version 1." UserInfo={NSLocalizedDescription=Provided schema version 0 is less than last set version 1., Error Code=1}

解决方案

1. 错误原因

修改Realm对象结构(添加新属性)后,未同步更新数据库的Schema版本,导致当前代码使用的版本号低于设备中已存在的数据库版本,触发版本不匹配错误。

2. 两种解决方式

方式一:更新Schema版本并配置迁移(保留现有数据,推荐)

在App启动阶段配置Realm的版本和迁移逻辑,确保结构修改后数据能平滑迁移:

import RealmSwift

func setupRealmConfiguration() {
    let realmConfig = Realm.Configuration(
        // 将版本号设为比现有版本大的数值(比如原版本是1,现在设为2)
        schemaVersion: 2,
        migrationBlock: { migration, oldVersion in
            // 根据旧版本号处理迁移逻辑
            if oldVersion < 2 {
                // 若新属性是可选类型/有默认值,这里无需额外操作,Realm自动处理
                // 若新属性是必填无默认值,需给旧数据设置初始值,示例:
                // migration.enumerateObjects(ofType: YourRealmModel.className()) { oldObj, newObj in
                //     newObj!["newProperty"] = "default_value"
                // }
            }
        }
    )
    Realm.Configuration.defaultConfiguration = realmConfig
    
    // 触发迁移验证
    do {
        _ = try Realm()
    } catch {
        print("Realm迁移失败:\(error.localizedDescription)")
    }
}

在App入口调用配置函数:

@main
struct YourSwiftUIApp: App {
    init() {
        setupRealmConfiguration()
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

方式二:重置Realm数据库(丢失所有数据,仅测试用)

开发测试阶段若无需保留数据,可直接删除现有数据库文件:

func resetRealmDatabase() {
    let defaultConfig = Realm.Configuration.defaultConfiguration
    guard let fileURL = defaultConfig.fileURL else { return }
    
    let filePaths = [
        fileURL,
        fileURL.appendingPathExtension("lock"),
        fileURL.appendingPathExtension("management")
    ]
    
    for path in filePaths {
        try? FileManager.default.removeItem(at: path)
    }
}

同样在App启动时调用该函数即可,注意上线版本禁止使用此方法。

3. 注意事项

  • 每次修改Realm对象结构(增删属性、修改类型等),都要将schemaVersion递增1。
  • 避免使用try!直接初始化Realm,改用do-catch捕获异常,减少崩溃风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:02:11