2016-04-07 9 views
0

約30,000レコードのjsonデータセットをRealmデータベースに一括インポートする必要があります。リポジトリオブジェクトのインポートのためにリポジトリオブジェクトをAnyObjectに変換できません

マイデコード可能なセットアップ:私は、レルムのインポートについては

struct Repository { 
    let xxxx:Int 
    let xxxx:String 
    let xxxx:String 
    let xxxx:Int 
    let xxxx:String 
    let xxxx:String 
    let xxxx:String 
} 

extension Repository : Decodable { 
    static func decode(json: AnyObject) throws -> Repository { 
     return try Repository(
      xxxx: json => "xxxx", 
      xxxx: json => "xxxx", 
      xxxx: json => "xxxx", 
      xxxx: json => "xxxx", 
      xxxx: json => "xxxx", 
      xxxx: json => "xxxx", 
      xxxx: json => "xxxx" 
     ) 
    } 
} 

    let config = Realm.Configuration(
         path: utility.getDocumentsDirectory().stringByAppendingPathComponent("Meta.realm"), 
         readOnly: false) 

        let realm = try! Realm(configuration: config) 

        try! realm.write { 
         let json = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: []) 
         let repo = try! [Repository].decode(json) 

         realm.create(Meta.self, value: repo, update: true) 
        } 

問題はレポオブジェクトでは、復号可能なため、カスタムクラス/オブジェクトの型でありますrealm.createの値ラベルのためにAnyObjectに変換できません

答えて

0

レルムはオブジェクトが 'Object'という特別なクラスから派生している必要があります。

あなたは、クラスにあなたの構造体を変更し、あなたがObjectから派生確保する必要があります。

class Repository : Object { 
    dynamic var xxxx:Int 
    dynamic var xxxx:String 
    dynamic var xxxx:String 
    dynamic var xxxx:Int 
    dynamic var xxxx:String 
    dynamic var xxxx:String 
    dynamic var xxxx:String 
} 

extension Repository : Decodable { 
    static func decode(json: AnyObject) throws -> Repository { 
     return try Repository(
      xxxx: json => "xxxx", 
      xxxx: json => "xxxx", 
      xxxx: json => "xxxx", 
      xxxx: json => "xxxx", 
      xxxx: json => "xxxx", 
      xxxx: json => "xxxx", 
      xxxx: json => "xxxx" 
     ) 
    } 
} 

//今、あなたはレルムにあなたのリポジトリオブジェクトを保存することができるはずです。

+0

残念ながら、上記の変更を加えるとエラーが発生します。 '非finalクラスのメソッド解読リポジトリはプロトコルに準拠するためにselfを返す必要がありますDecodable'また、 'Repository'タイプのイニシャライザを呼び出せません。 上記のコードはデコード可能なドキュメントですが、残念ながらオブジェクトを返さないのは、レルムごとのドキュメントではうまく動作するはずです。 – Sean

+0

しかしあなたの答えは私を正しい方向に導いてくれました。構造体をクラスにして拡張を取り除かなければならなかった。 リポジトリ:オブジェクト、デコード可能なクラスとして定義して終了し、初期化子を作成してスローするなどしました。 – Sean

関連する問題