【问题标题】:Realm migration oneToMany领域迁移 oneToMany
【发布时间】:2019-11-15 18:33:53
【问题描述】:

我需要一些迁移方面的帮助。

我有这个模型:

class Item: Object {
    @objc dynamic var title: String = ""
    @objc dynamic var done: Bool = false
}

新的迁移,有2个模型:

class Item: Object {
    @objc dynamic var title: String = ""
    @objc dynamic var done: Bool = false
    let category = LinkingObjects(fromType: Category.self, property: "items")
}
class Category: Object {
    @objc dynamic var id = NSUUID().uuidString
    @objc dynamic var name: String = ""
    var items = List<Item>()

    override class func primaryKey() -> String {
        return "id"
    }
}

我们无法为新项目创建新类别,并且最后一个项目是孤立的。 我必须创建一个“无类别”的新类别并在其中添加旧项目。

我试过了,但我没有成功:

private func zeroToOne(_ migration: Migration, _ oldSchemaVersion: UInt64) -> Void {        
        let category = Category()
        category.name = "No Category"        

        migration.enumerateObjects(ofType: Item.className()) { oldObject, newObject in
            let item = Item()
            item.title = newObject?["title"] as! String
            item.done = newObject?["done"] as! Bool
            category.items.append(item)
        }
        print("and migration")
    }

var configuration: Realm.Configuration {
        let config = Realm.Configuration(schemaVersion: 2, migrationBlock: { (migration, oldVersion) in
            if oldVersion < 3 {
                self.zeroToOne(migration, oldVersion)
            }
        })
        Realm.Configuration.defaultConfiguration = config
        return config
    }

private func initRealm() {
        do {
            self.realm = try Realm(configuration: configuration)
        } catch let error {
            print(error.localizedDescription)
            fatalError("Doenst work Realm")
        }
    }

提前感谢那些帮助我的人,谢谢:)

【问题讨论】:

    标签: ios swift iphone realm


    【解决方案1】:

    我使用它并且工作!

     private func zeroToOne(_ migration: Migration, _ oldSchemaVersion: UInt64) -> Void {
            let category = migration.create(Category.className())
            category["name"] = "No Category"
            category["id"] = NSUUID().uuidString
            migration.enumerateObjects(ofType: Item.className()) { oldObject, newObject in
                if let items = category["items"] as? List<MigrationObject>, let item = newObject {
                    items.append(item)
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多