2015-09-23 150 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答案,對不起。