2016-11-10 105 views
0

我有三個對象:境界遷移:從一個物體移動對象的另一個對象

class Customer: Object { 
    dynamic var solution: Solution!; 
    ... 
} 

class Solution: Object { 
    dynamic var data: Data!; 
    ... 
} 

class Data: Object { 
    ... 
} 

現在我需要的Data對象移動從SolutionCustomer使之成爲:

class Customer: Object { 
    dynamic var solution: Solution!; 
    dynamic var data: Data!; 
    ... 
} 

我不知道如何實現我的Realm Migration方法,以便一切正常,並且我不會丟失數據。

回答

2

我做了一些實驗與境界遷移示例應用程序,並與該潛在的解決方案提出了:

在遷移塊,你只能通過migration對象的境界文件交互。在遷移過程中直接訪問Realm文件的任何嘗試都將導致異常。

這就是說,可以嵌套調用migration.enumerateObjects引用不同的Realm模型對象類。因此,它應該只是一個初始枚舉對象的事情,並且在每次迭代中,通過Solution對象枚舉來找到具有正確值data的相應對象。一旦找到,應該可以使用來自Solution對象的數據設置對象Customer

Realm.Configuration.defaultConfiguration = Realm.Configuration(
    schemaVersion: 1, 
    migrationBlock: { migration, oldSchemaVersion in 
     if (oldSchemaVersion < 1) { 
      migration.enumerateObjects(ofType: Customer.className()) { oldCustomerObject, newCustomerObject in 
       migration.enumerateObjects(ofType: Solution.className()) { oldSolutionObject, newSolutionObject in 
        //Check that the solution object is the one referenced by the customer 
        guard oldCustomerObject["solution"].isEqual(oldSolutionObject) else { return } 
        //Copy the data 
        newCustomerObject["data"] = oldSolutionObject["data"] 
       } 
      } 
     } 
    } 
}) 

我覺得我需要強調的是,這段代碼絕不是經過測試,並保證能夠在當前狀態下工作。因此,我建議您確保您對一些預先不會錯過的虛擬數據進行徹底測試。 :)

0

夫特4,境界3

我不得不遷移鏈接到另一個對象的境界對象。我想刪除顯式鏈接並將其替換爲對象ID。 TiM的解決方案讓我獲得了大部分途徑,只需要一點點改進。

var config = Realm.Configuration() 
    config.migrationBlock = { migration, oldSchemaVersion in 
     if oldSchemaVersion < CURRENT_SCHEMA_VERSION { 

      // enumerate the first object type 
      migration.enumerateObjects(ofType: Message.className()) { (oldMsg, newMsg) in 

       // extract the linked object and cast from Any to DynamicObject 
       if let msgAcct = oldMsg?["account"] as? DynamicObject { 

        // enumerate the 2nd object type 
        migration.enumerateObjects(ofType: Account.className()) { (oldAcct, newAcct) in 
         if let oldAcct = oldAcct { 

          // compare the extracted object to the enumerated object 
          if msgAcct.isEqual(oldAcct) { 

           // success! 
           newMsg?["accountId"] = oldAcct["accountId"] 
          } 
         } 
        } 
       } 
      } 
     }