2016-11-10 7 views
0

私は3つのオブジェクトがあります。レルムの移行:別のオブジェクトに1つのオブジェクトからオブジェクトを移動

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

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

class Data: Object { 
    ... 
} 

は、今私はそれがなるようにSolutionからCustomerDataオブジェクトを移動する必要があります。

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

どのようにしてRealm Migrationメソッドを実装しなければならないので、すべてがうまく動作し、データが失われることはありません。私は、レルムの移行のサンプルアプリでいくつかの実験を行なったし、この潜在的な解決策を考え出した

答えて

2

:移行ブロックで

、あなただけのmigrationオブジェクトを介して自分のレルムファイルと対話することができます。移行中にRealmファイルに直接アクセスしようとすると、例外が発生します。

つまり、異なるRealmモデルオブジェクトクラスを参照するネストされた呼び出しをmigration.enumerateObjectsにすることができます。したがって、最初にCustomerオブジェクトを列挙し、各繰り返しで、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"] 
          } 
         } 
        } 
       } 
      } 
     } 
関連する問題