在swift中保存coredata中的json数据
我正在尝试保存应用程序包中的json数据。但它不是保存所有数据,而是只保存一个数据在swift中保存coredata中的json数据,json,swift,Json,Swift,我正在尝试保存应用程序包中的json数据。但它不是保存所有数据,而是只保存一个数据 func getDignosysListFromJson() { let coreData = CoreDataStack() let managedObjectContext = coreData.persistentContainer.viewContext let dignose = Dignose(context: managedOb
func getDignosysListFromJson() {
let coreData = CoreDataStack()
let managedObjectContext = coreData.persistentContainer.viewContext
let dignose = Dignose(context: managedObjectContext)
let jsonPath = Bundle.main.path(forResource: "dignosys", ofType: "json")
let jsonUrl = URL(fileURLWithPath: jsonPath!)
do {
let data = try Data(contentsOf: jsonUrl)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
if let newResult = jsonResult as? Array<Dictionary<String, Any>>{
for i in newResult{
let newName = i["dx description"] as! String
print(newName)
dignose.name = newName
dignose.date = "29 Dec 2020"
}
coreData.saveContext()
}
} catch {
print("")
}
}
移动线路
let dignose = Dignose(context: managedObjectContext)
进入循环
for i in newResult {
let dignose = Dignose(context: managedObjectContext)
let newName = i["dx description"] as! String
print(newName)
dignose.name = newName
dignose.date = "29 Dec 2020"
}
在每次迭代中获得一个新实例
该准则包含一些有问题的做法。我推荐这个
func getDignosysListFromJson() {
let coreData = CoreDataStack()
let managedObjectContext = coreData.persistentContainer.viewContext
let jsonUrl = Bundle.main.url(forResource: "dignosys", withExtension: "json")!
do {
let data = try Data(contentsOf: jsonUrl)
if let jsonResult = try JSONSerialization.jsonObject(with: data) as? [[String:Any]] {
for anItem in jsonResult {
let dignose = Dignose(context: managedObjectContext)
let newName = anItem["dx description"] as! String
print(newName)
dignose.name = newName
dignose.date = "29 Dec 2020"
}
coreData.saveContext()
}
} catch {
print(error)
}
}
移动线路
let dignose = Dignose(context: managedObjectContext)
进入循环
for i in newResult {
let dignose = Dignose(context: managedObjectContext)
let newName = i["dx description"] as! String
print(newName)
dignose.name = newName
dignose.date = "29 Dec 2020"
}
在每次迭代中获得一个新实例
该准则包含一些有问题的做法。我推荐这个
func getDignosysListFromJson() {
let coreData = CoreDataStack()
let managedObjectContext = coreData.persistentContainer.viewContext
let jsonUrl = Bundle.main.url(forResource: "dignosys", withExtension: "json")!
do {
let data = try Data(contentsOf: jsonUrl)
if let jsonResult = try JSONSerialization.jsonObject(with: data) as? [[String:Any]] {
for anItem in jsonResult {
let dignose = Dignose(context: managedObjectContext)
let newName = anItem["dx description"] as! String
print(newName)
dignose.name = newName
dignose.date = "29 Dec 2020"
}
coreData.saveContext()
}
} catch {
print(error)
}
}