如何在RealmSwift中避免迁移

kan*_*ris 13 migration realm swift

我只是使用Realm测试一些配置,因此我在我的领域类中添加和删除了变量和列表.由于我只是在测试,我不想经历迁移过程 - 我也没有任何影响连续性的数据.

有没有办法绕过Realm自动请求的迁移?

kis*_*umi 25

无论架构更改如何,有两种方法可以跳过迁移错误.

  1. 使用deleteRealmIfMigrationNeeded财产.如果是true,则在需要迁移时使用提供的架构重新创建Realm文件.

    let config = Realm.Configuration(deleteRealmIfMigrationNeeded: true)
    Realm.Configuration.defaultConfiguration = config
    
    let realm = try! Realm()
    ...
    
    Run Code Online (Sandbox Code Playgroud)

  2. 每次启动时增加架构版本.Realm具有自动迁移功能.如果您不需要迁移现有数据,则只需增加模式版本即可.架构将由Realm自动更改.

    let config = Realm.Configuration(schemaVersion: try! schemaVersionAtURL(Realm.Configuration.defaultConfiguration.fileURL!) + 1)
    Realm.Configuration.defaultConfiguration = config
    
    let realm = try! Realm()
    ...
    
    Run Code Online (Sandbox Code Playgroud)


jai*_*jan 9

在Swift 3中

通过将此代码放在AppDelegate类的"didFinishLaunchingWithOptions"方法中,可以轻松避免Realm中的迁移.

var config = Realm.Configuration()
config.deleteRealmIfMigrationNeeded = true
Realm.Configuration.defaultConfiguration = config
Run Code Online (Sandbox Code Playgroud)

如果使用新设置进行迁移,这将删除领域数据库.