领域迁移不起作用

use*_*936 14 realm ios swift2

    let config = Realm.Configuration(
        // Set the new schema version. This must be greater than the previously used
        // version (if you've never set a schema version before, the version is 0).
        schemaVersion: 1,

        // Set the block which will be called automatically when opening a Realm with
        // a schema version lower than the one set above
        migrationBlock: { migration, oldSchemaVersion in
            // We haven’t migrated anything yet, so oldSchemaVersion == 0
            if (oldSchemaVersion < 1) {
                // Nothing to do!
                // Realm will automatically detect new properties and removed properties
                // And will update the schema on disk automatically
            }
    })

    // Tell Realm to use this new configuration object for the default Realm
    Realm.Configuration.defaultConfiguration = config

    // Now that we've told Realm how to handle the schema change, opening the file
    // will automatically perform the migration
    let realm = try! Realm()
Run Code Online (Sandbox Code Playgroud)

这被放在应用程序中(应用程序:didFinishLaunchingWithOptions :)

在我的测试程序中,我更改了对象中的字段.我想删除数据库中的所有内容,然后转到新的字段类型.我从文档中复制了上面的代码,但似乎什么也没做.我仍然遇到这些错误:

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=0 "Migration is required due to the following errors: 
- Property types for 'unit' property do not match. Old type 'string', new type 'int'
- Property 'reps' has been added to latest object model." UserInfo={NSLocalizedDescription=Migration is required due to the following errors: 
- Property types for 'unit' property do not match. Old type 'string', new type 'int'
- Property 'reps' has been added to latest object model.}: file   /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-700.1.101.15/src/swift/stdlib/public/core/
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Geo*_*rna 14

尽管事实上我添加了默认的迁移代码,但我的应用程序崩溃了,我遇到了类似的问题 didFinishLaunchingWithOptions

问题是我确实在我的第一个视图控制器中初始化了一个Realm实例作为类级属性.因此从我的第一个ViewController中删除该类级别的realm对象修复了该问题.

import UIKit
import RealmSwift

class ViewController: UIViewController{
  let db = try! Realm() // Removing this solved my issue

  func doSomething(){
    let db = try! Realm() // Placed this here instead
  }
}
Run Code Online (Sandbox Code Playgroud)

我改为在需要它的函数内部创建了对象,无论如何这是一种更好的方法.


mar*_*ius 5

只要您仅进行本地开发,我建议您重置 Realm 数据库而不是进行迁移。如果您已经发布了具有其他架构的应用程序版本并希望保留用户数据,则迁移是可行的方法。

您可以通过从模拟器或设备中删除应用程序来删除数据库。或者,您可以使用NSFileManager在访问数据库之前删除 Realm 文件。

let defaultPath = Realm.Configuration.defaultConfiguration.path!
try NSFileManager.defaultManager().removeItemAtPath(defaultPath)
Run Code Online (Sandbox Code Playgroud)

  • 这并没有解决真正的问题,而只是建议对生产应用程序使用迁移。 (12认同)