谁可以帮助我提供代码?
我需要导入/预加载我的JSON 我的数据模型具有三个实体以及彼此之间的关系
喜欢商品和类别
如果应用程序是首次启动,我想导入所有项目并给他们一个类别。
但是,如果我这样做,如果我在其他物品上使用cat01,它也会被插入几次。我想插入500个项目,并将关系设置为仅5个类别-我该怎么做?有时一个项目有两个类别?
感谢帮助。
"entity1":
[{
"name": "Item1",
"info": "Loremipsum",
"categorie": {
"cat": "cat01"
},
"entity2": [{
"name": "ItemWithRelationship",
"info": "LoremipsumDolor"
}]
}]
//Preload - Relationships 2
fileprivate func preloadWithRelationshipsDECODE() {
guard let preloadFileURL = Bundle.main.url(forResource: "preload_DB", withExtension: "json") else {
return
}
guard let data = try? Data(contentsOf: preloadFileURL) else {
return
}
do {
//mit Array MIT Relationship
let results = try JSONDecoder().decode(Raum.self, from: data)
print(results.raum.count)
for result in results.entity1{
//Raum-DB
let entityRaum: String = String(describing: Raumliste.self)
let room = NSEntityDescription.insertNewObject(forEntityName: entityRaum, into: self.managedContext) as! Raumliste
room.name = result.name
room.info = result.info
//Categorie
let entityCat: String = String(describing: categorie.self)
let cat = NSEntityDescription.insertNewObject(forEntityName: entityCat, into: self.managedContext) as! Categorie
cat.name = result.categorie?.cat
myCat.categorie_rls = cat
myCat.categorie_rls?.name = result.categorie?.cat
for task in result.entity2!{
//Entitiy2-DB
let entityNR2: String = String(describing: MyEntity.self)
let extra = NSEntityDescription.insertNewObject(forEntityName: entityNR2, into: self.managedContext) as! MyEntity
extra.name = task.name!
room.addToExtraListe_rls(extra)
extra.info = task.info!
room.addToExtraListe_rls(extra)
saveContext()
}
do {
try managedContext.save()
print("gespeichert")
} catch {
print("Error saving todo: \(error)")
print ("No value associated with key someKey (\"actual_key_if_you_defined_your_own\").")
}
}
} catch let error as NSError {
print("Fehler: \(error.localizedDescription)")
}
}