迁移Realm中的主键

时间:2015-09-23 19:25:24

标签: ios swift realm

我刚刚在我的Realm模型中添加了一个主键,因此我一直在低于错误。我试图在appdelegate中迁移,但仍然得到了恐怖。我所做的就是添加propertyKey()功能。我该如何正确迁移?

Migration is required for object type 'Organization' due to the following errors:
- Property 'id' has been made a primary key."

但是我已经在下面添加了appdelegate:

    Realm.Configuration.defaultConfiguration = Realm.Configuration(
        schemaVersion: 1,
        migrationBlock: { migration, oldSchemaVersion in
            if (oldSchemaVersion < 1) {
                // The enumerate(_:_:) method iterates
                // over every Person object stored in the Realm file
                migration.enumerate(Organization.className()) { oldObject, newObject in
                    // combine name fields into a single field

                }
            }
    })

这是我的对象

class Location: Object {
    var id: Int = 0
    var longitude: Double = 0
    var latitude: Double = 0

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

}

class Organization: Object {
    var id: Int = 0
    var name: String = ""
    var image: NSData = NSData()
    let locations = List<Location>()

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

3 个答案:

答案 0 :(得分:5)

如果模型之前没有主键,您可以通过这样做来修复它:

// Changes the coordinate to new values
public void setLocation(int x, int y)
{/*write the code for here*/}

//Shift the point by the translation T<x+h,y+k>
public void translate(int h, int k)
{/*write the code for here*/}

我希望它有所帮助,
干杯!

答案 1 :(得分:1)

  1. 打开AppDelegate.swift
  2. 将以下代码添加到func应用程序中:

    let config = Realm.Configuration(
    
    // set a new version number, the version number must bigger than before
    
        // if you never set it, it's 0
    
        schemaVersion: 1,
    
        migrationBlock: { migration, oldSchemaVersion in
    
        if (oldSchemaVersion < 1) {
          // do nothing
          }
        })
    
        // tell Realm the new config should be used 
    
        Realm.Configuration.defaultConfiguration = config
    
        // open realm file and it will do auto-migration
    
        let realm = Realm()
    

答案 2 :(得分:1)

更新:在Realm 2.8.3上,迁移不再需要属性primaryKeyProperty

我无法编辑ReCamilio的答案,抱歉。