我需要将大约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
答案 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中。