在迁移期间添加和删除Realm.Object

voi*_*ref 2 migration realm swift

我正在进行迁移,需要从领域中删除对象并用不同的类型替换它们.

简而言之,我曾经只有一种类型,现在正在创建一个层次结构,所以BaseItem现在需要是一个DerivedItem.

我不确定实现这一目标的最佳方法.

这是我要尝试的内容:

setSchemaVersion(kSchemaVersion, Realm.defaultPath, { migration, oldSchemaVersion in
    if oldSchemaVersion == 0 {
        let realm = Realm()
        realm.write({ () -> Void in
            old = oldObject!    
            if old["type"] as! Int == 1 {
                let textItem = TextItem()
                textItem.text = old["text"] as! String
                copyBaseItemCommon(old, textItem)
                realm.add(textItem)
                realm.delete(newObject!)
     }
})
Run Code Online (Sandbox Code Playgroud)

这些是添加和删除的方式吗?

更新:

试过这个和第3行中的代码死锁: let realm = Realm()

任何人都知道进行此类迁移的技术是什么?

pte*_*fil 10

下载Realm时,您有一个Example项目.打开它,你有一个迁移演示.

这是他们进行迁移的方式:

let migrationBlock: MigrationBlock = { migration, oldSchemaVersion in
    if oldSchemaVersion < 1 {
        migration.enumerate(Person.className()) { oldObject, newObject in
            if oldSchemaVersion < 1 {
                // combine name fields into a single field
                let firstName = oldObject!["firstName"] as! String
                let lastName = oldObject!["lastName"] as! String
                newObject?["fullName"] = "\(firstName) \(lastName)"
            }
        }
    }
}
setDefaultRealmSchemaVersion(1, migrationBlock)
Run Code Online (Sandbox Code Playgroud)

如果您查看文档以进行迁移,您将看到在迁移中有一些创建和删除方法:

/**
    Create an `Object` of type `className` in the Realm being migrated.

    :param: className The name of the `Object` class to create.
    :param: object    The object used to populate the object. This can be any key/value coding
                      compliant object, or a JSON object such as those returned from the methods in
                      `NSJSONSerialization`, or an `Array` with one object for each persisted
                      property. An exception will be thrown if any required properties are not
                      present and no default is set.

    :returns: The created object.
    */
func create(className: String, value: AnyObject = default) -> RealmSwift.MigrationObject

/**
    Delete an object from a Realm during a migration. This can be called within
    `enumerate(_:block:)`.

    :param: object Object to be deleted from the Realm being migrated.
    */
func delete(object: RealmSwift.MigrationObject)
Run Code Online (Sandbox Code Playgroud)

你可以像这样在迁移块中使用它们migration.create("TextItem", oldObject!).

请记住,在迁移中,您使用的是migration对象,而不是Realm.