无法将存储库对象转换为AnyObject以进行导入

时间:2016-04-07 01:59:37

标签: swift realm

我需要将大约30,000条记录的json数据集批量导入Realm数据库。

我对存储库对象的可解码设置:

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)
                    }

问题是repo对象是Decodable的自定义类/对象类型,并且不能转换为Realm.create中值标签的AnyObject

1 个答案:

答案 0 :(得分:0)

Realm要求您的对象派生自一个名为“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"
        )
    }
}

//现在您应该能够将Repository对象保存到Realm中。