我正在学习Realm并正在转换我的实验应用程序/游戏,它使用数组到Realm;
它通过本地JSON文件和ObjectMapper加载预播种数据;然后在领域中创建对象;这部分似乎有用。
// Parse response
let json = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Array<Dictionary<String, AnyObject>>
let factories = Mapper<Factory>().mapArray(JSONArray: json)!
do {
let realm = try Realm()
try realm.write {
for factory in factories
{
realm.add(factory, update: true)
}
}
} catch let error as NSError {
print(error.localizedDescription as Any)
}
我遇到的问题是它映射的时候;我希望它能同时创建它的子对象并将它们链接到父对象。
每个父母(Factory
)都有大约4个与之相关联的子女(Engine
)。
// Factory is parent object
class Factory: Object, Mappable {
dynamic var name: String = ""
let engines = List<Engine>()
//Impl. of Mappable protocol
required convenience init?(map: Map) {
self.init()
}
// Mappable
func mapping(map: Map) {
name <- map["name"]
}
}
// Engine is a child to Factory
class Engine: Object {
dynamic var production: Int = 0
// create children and add to the parent factory
static func createEngines(parent:Factory) -> [Engines]
{
var engines:[Engine] = [Engine]()
for _ in stride(from:0, to: 3, by: 1) {
//let engine : Engine = Engine.init(parent: element)
//engines.append(engine)
}
return engines
}
}
如果我试图把它放在我的mappable中
engines = Engine.createEngines(parent: self)
并在我的工厂模型中进行更改;
`var engines = List<Engine>()`
我收到此错误:
Cannot assign value of type '[Engine]?' to type 'List<Engine>'
这里的问题是,简单地创建一个引擎数组(子项),将它附加到数组似乎不适用于Realm,我不知道如何做到这一点。
因此,我的问题是如何批量创建子项,将其分配给给定父项并将其添加到当前域写/保存?
非常感谢。
答案 0 :(得分:1)
Jerrot here on Githib Gist
有一个非常好的解决方案映射应该在主模型对象中定义,如下所示:
func mapping(map: Map) {
title <- map["title"]
products <- (map["products"], ArrayTransform<ProductModel>())
}
真正的魔力发生在ArrayTransform
类:
func transformFromJSON(value: AnyObject?) -> List<T>? {
var result = List<T>()
if let tempArr = value as! Array<AnyObject>? {
for entry in tempArr {
let mapper = Mapper<T>()
let model : T = mapper.map(entry)!
result.append(model)
}
}
return result
}
答案 1 :(得分:1)
我改变了我的代码来执行此操作;
我不确定我是否做得对,但似乎有效。
我只是不喜欢我必须硬连接父母;因为我认为Realm / ObjectMapper可以为我做到这一点。但它不是一个主要问题,因为只有大约3或4个关系。
let factories = Mapper<Factory>().mapArray(JSONArray: json)!
do {
let realm = try Realm()
try realm.write {
for f in factories
{
realm.add(f, update: true)
}
let factories = realm.objects(Factory.self)
print (factories.count) // for debug purposes
for f in factories {
for _ in stride(from: 0, to: f.qty, by: 1) {
let engine : Engine = Engine.init()
engine.parent = f
f.engines.append(engine)
}
}
}
} catch let error as NSError {
print(error.localizedDescription as Any)
}
以上代码似乎为我做了工作;虽然我希望我不必手动设置父(engine.parent = f
)
无论如何,我接受了@ BogdanFarca的回答。