Swift:如何迁移自定义领域

时间:2019-01-18 06:55:44

标签: ios swift realm

我正在尝试对自定义Realm文件进行迁移。请注意,在该项目中,我在默认领域文件之上有两个自定义领域文件,分别是Photo.realmTransport.realm。我已经为Photo对象添加了一个新属性,如下所示:

class Photo: Object {
    @objc dynamic var id: String? = nil
    @objc dynamic var secret: String? = nil
    @objc dynamic var server: String? = nil
    @objc dynamic var farm: Int = 0
    @objc dynamic var imageData: Data? = nil
    @objc dynamic var tranport: Transport? //Newly added attribute
}

并且想要迁移。我已经阅读了文档,并且由于我正在迁移自定义领域文件,因此我修改了代码并将其添加到didFinishLaunchingWithOptions中,如下所示:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let defaultConfig = Realm.Configuration()

    if let fileURL = defaultConfig.fileURL {
        let photoRealmFileURL = fileURL.deletingLastPathComponent().appendingPathComponent("Photo.realm")
        let photoMigrationConfig = Realm.Configuration(fileURL: photoRealmFileURL, schemaVersion: 1, migrationBlock: { (migration, oldSchemaVersion) in
            if (oldSchemaVersion < 1) {

            }
        }, objectTypes: [Photo.self])

        do {
            let _ = try Realm(configuration: photoMigrationConfig)
        } catch let error {
            print("Migration Error", error.localizedDescription)
        }

    }

    return true
}

在HomeController上,我像这样初始化自己的领域:

class HomeController: UICollectionViewController {

    var photoRealm = try! Realm()
    var transportRealm = try! Realm()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupRealm()
    }

    fileprivate func setupRealm() {
        let defaultConfig = Realm.Configuration()

        if let fileURL = defaultConfig.fileURL {
            let photoRealmFileURL = fileURL.deletingLastPathComponent().appendingPathComponent("Photo.realm")
            let photoConfig = Realm.Configuration(fileURL: photoRealmFileURL, objectTypes: [Photo.self])

            let transportRealmFileURL = fileURL.deletingLastPathComponent().appendingPathComponent("Transport.realm")
            let tranportConfig = Realm.Configuration(fileURL: transportRealmFileURL, objectTypes: [Transport.self])

            do {
                photoRealm = try Realm(configuration: photoConfig)
                transportRealm = try Realm(configuration: tranportConfig)

                let cars = Transport()
                cars.name = "cars"

                let planes = Transport()
                planes.name = "planes"

                try transportRealm.write {
                    transportRealm.add(cars)
                    transportRealm.add(planes)
                }

            } catch let error {
                print("Error setting Realm", error.localizedDescription)
            }
        }
    }

有了这个,我抛出了错误:

  

线程1:致命错误:“尝试!”表达式意外引发错误:   错误Domain = io.realm代码= 10“由于以下原因,需要迁移   以下错误:   -已添加属性'Photo.tranport'。“ UserInfo = {NSLocalizedDescription =由于需要迁移   以下错误:   -已添加属性“ Photo.tranport”。,错误代码= 10}

我认为很明显迁移没有正确完成。当我迁移自定义领域而不是默认领域时,文档尚不清楚如何正确执行。有什么建议吗?谢谢。

1 个答案:

答案 0 :(得分:0)

  

您可以通过检查要更新的架构版本来迁移领域数据库。并将配置传递给默认   领域的配置。

将这些代码行添加到appDelegate的didFinishLaunchingWithOptions方法中。在完成领域配置后,对其进行必要的更改。

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

    if oldSchemaVersion < 1 {
     // Add your class name where you have added new property 'tranport'.
      migration.enumerate(Photo.className()) { oldObject, newObject in
        newObject?["tranport"] = "Your value"
      }    
    }
  }
) 
Realm.Configuration.defaultConfiguration = config