2016-02-07 79 views
0

比方說,你有一個像與非標準化數據域遷移

class Person: Object { 
    var dynamic firstName: String = "" 
    var dynamic lastName: String = "" 
} 

境界對象現在,我想升級數據庫,並提取出姓氏進入一個新的類像這樣

class LastName: Object { 
    var dynamic sirName: String = "" 

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

class Person: Object { 
    var dynamic firstName: String = "" 
    var dynamic lastName: LastName! 
} 

什麼遷移看起來像什麼?我嘗試了一個簡單的遷移,但這可能會導致具有相同primaryKey的多個LastName對象。

回答

0

在你AppDelegatedidFinishLaunchingWithOptions

let configuration = Realm.Configuration(
    schemaVersion: 1, //This must be larger than the previous schemaVersion 
    migrationBlock: { migration, oldSchemaVersion in 
     if oldSchemaVersion < 1 { 
      migration.enumerate(Person.className()) { oldObject, newObject in 
       let lastName = oldObject!["lastName"] as! String 
       let newValue: [String: String] = ["sirName": lastName] 
       let createdObject = migration.create(LastName.className(), value: newValue) 
       newObject!["lastName"] = createdObject 
      } 
     } 
}) 

Realm.Configuration.defaultConfiguration = configuration // Set the new configuration as default 

let realm = try! Realm() // Open the default realm to perform the migration 

要添加,這現在有primaryKey作品以及與模型看起來像這樣:

class Person: Object { 
    dynamic var firstName: String = "" 
    dynamic var lastName: LastName! 
} 

class LastName: Object { 
    dynamic var sirName: String = "" 

    override static func primaryKey() -> String? { 
     return "sirName" 
    } 
} 

但這種遷移將無法正常工作如果由於primaryKey是每個對象的唯一標識符而存在lastName的重複項,則要麼確保不會有重複項,請使用另一個屬性作爲primaryKey或在LastName對象中完全不使用primaryKey

+0

這不起作用。它試圖設置一個字典到newObject![「lastName」]屬性 –

+0

@NoName對不起,修復它,它現在應該如此! – xoudini

+0

我相信這仍然可能會給出重複的姓氏對象具有相同的主鍵,從而給出錯誤 –