2015-09-23 119 views
2

我刚刚为我的Realm模型添加了主键,因此我一直收到以下错误。我试图在appdelegate中迁移,但仍然得到了错误。我所做的只是添加propertyKey()功能。我如何正确迁移?在Realm中迁移主键

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" 
    } 
} 

回答

5

如果模型没有之前有一个主键,你可以修复它这样做:

//MARK: Realm Migrations 
    Realm.Configuration.defaultConfiguration = Realm.Configuration(
     // bump the schema version to 2 
     schemaVersion: 2, 
     migrationBlock: { migration, oldSchemaVersion in 
      migration.enumerate(Organization.className()) { oldObject, newObject in 
       // make sure to check the version accordingly 
       if (oldSchemaVersion < 2) { 
        // the magic happens here: `id` is the property you specified 
        // as your primary key on your Model 
        newObject!["primaryKeyProperty"] = "id" 
       } 
      } 
     } 
    ) 

我希望它有帮助,
干杯!

+0

所以它会是newObject![“primaryKeyProperty”] = 0(或任何其他int) –

1
  1. 打开AppDelegate.swift
  2. 添加如下代码到FUNC应用:

    让配置= Realm.Configuration(

    //设置一个新的版本号,版本号必须大于前

    // 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() 
    
  3. 英语不好,但我希望它可以帮助你:)

0

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

我无法编辑ReCamilio答案,对不起。