在迁移过程中添加和删除Realm.Object

时间:2015-05-21 21:43:39

标签: swift migration realm

我正在进行迁移,需要从领域中删除对象并用其他类型替换它们。

简而言之,我曾经只有一种类型,现在正在创建一个层次结构,所以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!)
     }
})

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

更新:

尝试了这一点以及第3行中的代码死锁:let realm = Realm()

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

2 个答案:

答案 0 :(得分:10)

下载Realm时,您有一个示例项目。打开它,你就有了一个迁移演示。

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

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)

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

/**
    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)

您可以在迁移块中使用它们,例如migration.create("TextItem", oldObject!)

请记住,在迁移中,您使用migration对象,而不是领域。

答案 1 :(得分:-2)

你正在使用更新的领域吗?

基于文档..

你应该这样做&gt;&gt;

 let realm = Realm()

 realm.write
{
 realm.add(theObject)
 realm.delete(theObject)
}

希望它有所帮助!